Loading

【leetcode】993. Cousins in Binary Tree

  Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.

  Two nodes of a binary tree are cousins if they have the same depth with different parents.
  Note that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int dpx[2]={0,0};//0-parent node val 1-depth
    int dpy[2]={0,1};
    
    bool isCousins(TreeNode* root, int x, int y) {
        //递归遍历 存储父亲节点 和深度
        helper(root,0,0,x,y);
        return dpx[0]!=dpy[0] && dpx[1]==dpy[1]; 
    }
    
    void helper(TreeNode* node, int parent,int depth,int x,int y){
        if(node==nullptr) return;
        depth++;
        if(x==node->val){
            dpx[0]=parent;
            dpx[1]=depth;
            return;//剪枝
        }
        if(y==node->val){
            dpy[0]=parent;
            dpy[1]=depth;
            return;//剪枝
        }
        helper(node->left,node->val,depth,x,y);
        helper(node->right,node->val,depth,x,y);
        return;  
    }
};

 

posted @ 2021-11-20 14:43  aalanwyr  阅读(41)  评论(0编辑  收藏  举报