LeetCode 993. Cousins in Binary Tree

本文介绍了一种经典的二叉树问题——判断两个节点是否为堂兄弟节点,提供了宽度优先搜索(BFS)和深度优先搜索(DFS)两种解法。通过遍历二叉树,检查目标节点的深度和父节点,确保它们在同一层级但不同父节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这道题比较经典,并且有两种BFS和DFS两种解法,所以写一篇博客总结一下。代码里有注释,方便大家理解~

  1. Breadth-First Search
    /**
     * 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 {
        public boolean isCousins(TreeNode root, int x, int y) {
            Queue<TreeNode> q = new LinkedList<>();
            q.offer(root);
            //isEmpty() is a method inherited from interface java.util.Collection
            while(!q.isEmpty()){
                // Be cautious that we have to store the size of queue in advance
                // because q.size() will keep changing
                int size = q.size();
                boolean xExist = false;
                boolean yExist = false;
                // For loop controls the BFS breadth
                for(int i = 0; i < size; i++){
                    TreeNode cur = q.poll();
                    if(cur.val == x){
                        xExist = true;
                    }else if(cur.val == y){
                        yExist = true;
                    }
                    if(cur.left != null && cur.right != null){
                        if(cur.left.val == x && cur.right.val == y){
                            return false;
                        }else if(cur.left.val == y && cur.right.val == x){
                            return false;
                        }
                    }
                    if(cur.left != null){
                        q.offer(cur.left);
                    }
                    if(cur.right != null){
                        q.offer(cur.right);
                    }
                }
                if(xExist && yExist){
                    return true;
                }else if(xExist || yExist){
                    // If we only find one node in this level, we can conclude that they are not cousins.
                    return false;
                }
            }
            return false;
        }
    }

     

  2. Depth-First Search
    /**
     * 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 {
        // Initialization
        int xDepth = -1, yDepth = -1;
        TreeNode xParent, yParent;
        // We need to keep track of the depth and parent node, so we put them into the parameters of the dfs function.
        // Traverse the whole tree and find the nodes whose values are x and y respectively.
        private void dfs(TreeNode node, int x, int y, int depth, TreeNode parent){
            // base case
            if(node == null){
                return;
            }
            if(node.val == x){
                xDepth = depth;
                xParent = parent;
            }else if(node.val == y){
                yDepth = depth;
                yParent = parent;
            }else{
                // If we have found x or y, then we do not have to go further because cousins must have the same                   
                // depth.
                dfs(node.left, x, y, depth + 1, node);
                dfs(node.right, x, y, depth + 1, node);
            }
        }
        
        public boolean isCousins(TreeNode root, int x, int y) {
            dfs(root, x, y, 0, new TreeNode(0));
            return xDepth == yDepth && xParent != yParent;
        }
    }

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值