2023年12月5日 星期二

[872] Leaf-Similar Trees

果然是easy的歡樂題(?) 看來是沒有什麼厲害的解法了 (?)
有一個是用string 去存,最後strcmp 這樣。
感覺string 一直長大讓人很不安心!
還是用一個array 存int 們好了 XD
最後的for 迴圈原來也可以用memcpy 搞定,以上。

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void leaf(struct TreeNode* root, int *idx , int* array)
{
if (root == NULL)
return;
if (root->left == NULL && root->right == NULL)
{
(*idx)++;
array[*idx]= root->val;
return;
}
leaf(root->left, idx , array);
leaf(root->right, idx, array);
return;
}

bool leafSimilar(struct TreeNode* root1, struct TreeNode* root2) {
int *lv1 =calloc (200, sizeof (int));
int *lv2 =calloc (200, sizeof (int));
int idx1= -1, idx2=-1;
leaf(root1, &idx1, lv1);
leaf(root2, &idx2, lv2);
if (idx1 != idx2)
return false;
#if 1
for (int i=0;i<=idx1; i++)
{
if (lv1[i]!= lv2[i])
return false;
}
return true;
#else
return (memcmp(lv1,lv2,200) == 0 )? true:false;
#endif
}

沒有留言:

張貼留言