2022年11月5日 星期六

[993] Cousins in Binary Tree

感覺沒什麼秘技?!就是要多加一個parent 的紀錄
看是要跑兩次function check 還是要用一個global 紀錄parent ?!
或是用structure宣告一個typedef 是存parent and depth
總而言之呢~~~~
一開始求高度很快就寫好了~要加parent check 卡了一下. 以上
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int countDep(struct TreeNode* node, int val, int depth){
if (node == NULL)
return 0;
if (node->val == val)
return depth;
depth +=1;
return (countDep(node->left, val,depth) + countDep(node->right, val,depth));
}

bool checkParent(struct TreeNode* root, int x, int y)
{
if (root==NULL)
return false;
if (root->left == NULL)
return checkParent(root->right , x,y);
if (root->right == NULL)
return checkParent(root->left , x,y);

if (((root->left->val == x) && (root->right->val == y)) ||
((root->left->val == y) && (root->right->val == x)) )
return true;
return (checkParent(root->left , x, y) || checkParent(root->right , x,y));
}

bool isCousins(struct TreeNode* root, int x, int y){
int xHeight = countDep(root, x, 0);
int yHeight = countDep(root, y, 0);

if (xHeight == yHeight)
return !checkParent(root, x, y);
return false;
}

沒有留言:

張貼留言