当前位置:网站首页>【二叉树】993. Cousins in Binary Tree

【二叉树】993. Cousins in Binary Tree

2022-06-23 03:32:00 暮色_年华

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.

题意:定义堂兄弟节点:层数相同,但是父节点不相同。

思路:dfs,记录层数和父节点的值。

返回一个数组,里面存层数和父节点的值

class Solution {
    public boolean isCousins(TreeNode root, int x, int y) {
        int[] a = dfs(root,x,0,-1);
        int[] b = dfs(root,y,0,-1);
        if(a[0] == b[0]){
            return a[1] != b[1];
        }
        return false;
    }
    int[] dfs(TreeNode root,int x,int level,int p){
        if(root == null){
            return new int[]{};
        }
        if(root.val == x){
            return new int[]{level,p};
        }
        int[]a = dfs(root.left,x,level+1,root.val);
        int[]b = dfs(root.right,x,level+1,root.val);
        if(a.length == 0) return b;
        return a;
    }
}

原网站

版权声明
本文为[暮色_年华]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_52043808/article/details/125413340