判断二叉树的堂兄弟节点BFS+dfs

75 篇文章 0 订阅
15 篇文章 0 订阅

在这里插入图片描述
DFS

class Solution {
    int x, y;
    int depthX, depthY;
    TreeNode fatherX, fatherY;
    public boolean isCousins(TreeNode root, int x, int y) {
        this.x = x;
        this.y = y;
        getNodeDepthAndHisFather(root, null, 0);
        return (depthX == depthY) && (fatherX != fatherY);
    }
    void getNodeDepthAndHisFather(TreeNode root, TreeNode father, int depth){
        if(root == null) {return;}
        if(root.val == x) {
            this.depthX = depth;
            this.fatherX = father;
        }
        if(root.val == y) {
            this.depthY = depth;
            this.fatherY = father;
        }
        getNodeDepthAndHisFather(root.left, root, depth+1);
        getNodeDepthAndHisFather(root.right, root, depth+1);
    }
}
BFS
    public boolean isCousins(TreeNode root, int x, int y) {
        //两个队列一个存放树的节点,一个存放节点对应的值
        Queue<TreeNode> queue = new LinkedList<>();
        Queue<Integer> value = new LinkedList<>();
        queue.add(root);
        value.add(root.val);
        //如果队列不为空,说明树的节点没有遍历完,就继续遍历
        while (!queue.isEmpty()) {
            //BFS是从上到下一层一层的打印,levelSize表示
            //当前层的节点个数
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                //节点和节点值同时出队
                TreeNode poll = queue.poll();
                value.poll();
                //首先判断x和y是否是兄弟节点的值,也就是判断他们的父节点
                //是否是同一个
                if (poll.left != null && poll.right != null) {
                    if ((poll.left.val == x && poll.right.val == y) ||
                            (poll.left.val == y && poll.right.val == x)) {
                        return false;
                    }
                }
                //左子节点不为空加入到队列中
                if (poll.left != null) {
                    queue.offer(poll.left);
                    value.offer(poll.left.val);
                }
                //右子节点不为空加入到队列中
                if (poll.right != null) {
                    queue.offer(poll.right);
                    value.offer(poll.right.val);
                }
            }
            //判断当前层是否包含这两个节点的值,如果包含就是堂兄弟节点
            if (value.contains(x) && value.contains(y))
                return true;
        }
        return false;
    }



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值