993. 二叉树的堂兄弟节点

670 阅读1分钟

原题地址:993. 二叉树的堂兄弟节点

已知条件:

  1. 每个节点的值都是唯一的
  2. 只有满足父节点不同,但是在同一深度下的两个节点才是堂兄弟节点
  3. x不等于y
  4. 节点取值范围:1~100

解题思路

通过分析,该题的最终目的是要确定两个节点是否在同一层,因此推荐使用DFS广度优先的搜索模式,首先确定好DFS的核心代码:

Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while(!queue.isEmpty()){
    int size = queue.size();
    for(int i = 0; i < size; i++){
        TreeNode node = queue.poll();
        if(node.left != null){
            queue.add(node.left);
        }
        if(node.right != null){
            queue.add(node.right);
        }
    }
}

核心底层代码实现之后,现在需要考虑我们需要哪些参数

  1. 判断父节点是否一致,需要定义xParentIdyParentId分别来确定xy的父节点
  2. 判断是否在同一层级,需要定义xDepthyDepth来确定xy所在的层级
  3. 额外定义depth确定当前所在层级
  4. 额外定义xFoundyFound来表示xy是否被找到

完整代码如下:

public boolean isCousins(TreeNode root, int x, int y) {
        if(root == null || x == 0 || y == 0 || root.val == x || root.val == y){
            return false;
        }
        int xParentId = 0;
        boolean xFound = false;
        int xDepth = -1;

        int yParentId = 0;
        boolean yFound = false;
        int yDepth = -1;

        int depth = 0;

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0; i < size; i++){
                TreeNode node = queue.poll();
                if(node.left != null){
                    queue.add(node.left);
                    if(node.left.val == x){
                        xParentId = node.val;
                        xFound = true;
                        xDepth = depth;
                    }
                    if(node.left.val == y){
                        yParentId = node.val;
                        yFound = true;
                        yDepth = depth;
                    }
                }
                if(node.right != null){
                    queue.add(node.right);
                    if(node.right.val == x){
                        xParentId = node.val;
                        xFound = true;
                        xDepth = depth;
                    }
                    if(node.right.val == y){
                        yParentId = node.val;
                        yFound = true;
                        yDepth = depth;
                    }
                }
            }
            // 一旦X或Y在本层找到,直接弹出
            if(xFound || yFound){
                break;
            }
            // 增加深度
            depth++;
        }
        // x的父级与y的父级不等且X和Y所在的层级一致则说明两个节点在同一层级
        return xParentId != yParentId && xDepth == yDepth;
    }