LeetCode -- Cousins in Binary Tree 二叉树堂兄弟节点

188 阅读1分钟

In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.

Two nodes of a binary tree are cousins if they have the same depth, but have different parents.

We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.

Return true if and only if the nodes corresponding to the values x and y are cousins.

题目意思是:给定每个节点值唯一的二叉树,查找深度一样的堂兄弟节点(不能是同一父节点)。

解法:使用深度遍历,在dfs方法中,当找到了x或者y就不需要继续进行了,因为此时另一个节点要满足要求,必须在非当前节点的树下才行。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    TreeNode xParent = null,yParent = null;
    int xDepth = 0, yDepth = 0;
    public boolean isCousins(TreeNode root, int x, int y) {
        dfs(root, null, x, y, 0);
        return xParent != yParent && xDepth == yDepth;
    }
    void dfs(TreeNode root, TreeNode parent, int x, int y, int depth){
        if(root == null){
            return;
        }
        if(x == root.val){
            xParent = parent;
            xDepth = depth;
        }else if(y == root.val){
            yParent = parent;
            yDepth = depth;
        }else{
            dfs(root.left, root, x, y, depth+1);
            dfs(root.right, root, x, y, depth+1);
        }
    }
    
}