LeetCode.993-二叉树中的堂兄弟(Cousins in Binary Tree)

【Latex】【附安装文件】Miktex和TexStudio的安装与配置 这代表“构建并运行”,一般来说,我们只需要点这个按钮来运行Latex代码。保存一下代码文件,再运行一次,PDF文件会出现在与代码文件相同的文件夹下。安装完成后,你可能会跳转到一个页面中,你看到这个页面就意味着安装成功了。其实不需要你敲,你只要将下面的代码复制粘贴到你刚刚的文件中即可。成功安装MikTex后,我们需要进行更新,减少后续使用的麻烦。如果懂得将安装路径设置在你想要的盘中,你可以自己设置。双击上文的.exe文件后,你会看到如下画面。如果不懂,为避免不必要的麻烦,请直接点击“ 阅读详情

这是悦乐书的第374次更新,第401篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第235题(顺位题号是993)。在二叉树中,根节点在深度0处,并且每个深度为k的节点的子节点,他们深度为k + 1。

如果二元树的两个节点具有相同的深度但具有不同的父节点,则它们是堂兄弟。

我们给出了具有唯一值的二叉树root,以及树中两个不同节点的值x和y。

当且仅当对应于值x和y的节点是堂兄弟时,才返回true。例如:

输入:root = [1,2,3,4],x = 4,y = 3

      1
    /   \
   2     3
  / 
 4

输出:false


输入:root = [1,2,3,null,4,null,5],x = 5,y = 4

      1
    /   \
   2     3
    \     \
     4     5

输出:true


输入:root = [1,2,3,null,4],x = 2,y = 3

      1
    /   \
   2     3
    \ 
     4

输出:false

注意:

  • 树中的节点数将介于2和100之间。

  • 每个节点都有一个从1到100的唯一整数值。

02 第一种解法

题目的意思是x和y在同一层,但是他们的父级节点不一样,也就是x和y属于堂兄弟的关系。

使用BFS(广度优先)的算法,通过迭代的方式借助Stack来实现,使用了一个额外的方法,分别求出x和y的层级和他们的父级节点,用一个长度为2的数组返回,如果x和y的层级相同且父级结点不同,就返回true。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public boolean isCousins(TreeNode root, int x, int y) {
    int[] arr = getTreeDepth(root, x);
    int[] arr2 = getTreeDepth(root, y);
    if (arr.length < 1 || arr2.length < 1) {
        return false;
    }
    return arr[0] != arr2[0] && arr[1] == arr2[1];
}

public int[] getTreeDepth(TreeNode root, int num) {
    Stack<TreeNode> stack = new Stack<TreeNode>();
    stack.push(root);
    int depth = 0;
    while (!stack.isEmpty()) {
        Stack<TreeNode> stack2 = new Stack<TreeNode>();
        while (!stack.isEmpty()) {
            TreeNode tem = stack.pop();
            if (tem.left != null) {
                // 当前节点的左子节点值等于要找的数
                if (tem.left.val == num) {
                    return new int[] {tem.val, depth+1};
                }
                stack2.push(tem.left);
            }
            if (tem.right != null) {
                // 当前节点的右子节点值等于要找的数
                if (tem.right.val == num) {
                    return new int[] {tem.val, depth+1};
                }
                stack2.push(tem.right);
            }
        }
        stack = stack2;
        depth++;
    }
    return new int[] {};
}

03 第二种解法

针对第一种解法,我们也可以将判断的方法融合在一起,依旧是借助栈。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public boolean isCousins2(TreeNode root, int x, int y) {
    Stack<TreeNode> stack = new Stack<TreeNode>();
    stack.push(root);
    while (!stack.isEmpty()) {
        Stack<TreeNode> stack2 = new Stack<TreeNode>();
        boolean xExist = false, yExist = false;
        while (!stack.isEmpty()) {
            TreeNode tem = stack.pop();
            if (tem.val == x) {
                xExist = true;
            }
            if (tem.val == y) {
                yExist = true;
            }
            // x和y不能有同一个父节点
            if (tem.left != null && tem.right != null) {
                if (tem.left.val == x && tem.right.val == y) {
                    return false;
                }
                if (tem.left.val == y && tem.right.val == x) {
                    return false;
                }
            }
            if (tem.left != null) {
                stack2.push(tem.left);
            }
            if (tem.right != null) {
                stack2.push(tem.right);
            }
        }
        stack = stack2;
        if (xExist && yExist) {
            return true;
        }
    }
    return false;
}

04 第三种解法

和第二种解法思路一样,只是将栈换成了队列。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public boolean isCousins3(TreeNode root, int x, int y) {
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        int size = queue.size();
        boolean xExist = false, yExist = false;
        for (int i=0; i<size; i++) {
            TreeNode tem = queue.poll();
            if (tem.val == x) {
                xExist = true;
            }
            if (tem.val == y) {
                yExist = true;
            }
            // x和y不能有同一个父节点
            if (tem.left != null && tem.right != null) {
                if (tem.left.val == x && tem.right.val == y) {
                    return false;
                }
                if (tem.left.val == y && tem.right.val == x) {
                    return false;
                }
            }
            if (tem.left != null) {
                queue.offer(tem.left);
            }
            if (tem.right != null) {
                queue.offer(tem.right);
            }
        }
        if (xExist && yExist) {
            return true;
        }
    }
    return false;
}

05 第四种解法

借助递归,一个递归方法求深度,一个递归方法找父节点,最后判断深度是否相同且父节点不同。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public boolean isCousins4(TreeNode root, int x, int y) {
    return getDepth(root, x, 0) == getDepth(root, y, 0) && 
            findParent(root, x) != findParent(root, y);
}

public int getDepth(TreeNode root, int num, int depth){
    if (root == null) {
        return 0;
    }
    if (root.val == num) {
        return depth;
    }
    int left = getDepth(root.left, num, depth+1);
    int right = getDepth(root.right, num, depth+1);
    return Math.max(left, right);
}

public int findParent(TreeNode root, int num) {
    if (root == null) {
        return 0;
    }
    if (root.left != null && root.left.val == num) {
        return root.val;
    }
    if (root.right != null && root.right.val == num) {
        return root.val;
    }
    int left = findParent(root.left, num);
    int right = findParent(root.right, num);
    return Math.max(left, right);
}

06 第五种解法

我们也可以只是用一次递归方法,借助全局变量来解。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

private int depthX;
private int depthY;
private TreeNode parentX;
private TreeNode parentY;

public boolean isCousins5(TreeNode root, int x, int y) {
    helper(root, x, y, 0, null);
    return depthX == depthY && parentX != parentY;
}

public void helper(TreeNode root, int x, int y, int depth, TreeNode parent) {
    if (root == null) {
        return ;
    }
    if (root.val == x) {
        depthX = depth;
        parentX = parent;
    } else if (root.val == y) {
        depthY = depth;
        parentY = parent;
    }
    helper(root.left, x, y, depth+1, root);
    helper(root.right, x, y, depth+1, root);
}

07 第六种解法

我们还可以将第五种解法中找父节点的变量换成int类型,因为节点值唯一,可以直接使用节点值参与判断。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

private int depthX;
private int depthY;
private int parentX;
private int parentY;

public boolean isCousins6(TreeNode root, int x, int y) {
    helper(root, x, y, 0, 0);
    return depthX == depthY && parentX != parentY;
}

public void helper(TreeNode root, int x, int y, int depth, int parent) {
    if (root == null) {
        return ;
    }
    if (root.val == x) {
        depthX = depth;
        parentX = parent;
    } else if (root.val == y) {
        depthY = depth;
        parentY = parent;
    }
    helper(root.left, x, y, depth+1, root.val);
    helper(root.right, x, y, depth+1, root.val);
}

08 小结

算法专题目前已连续日更超过七个月,算法题文章241+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

Memory SystemsCache, DRAM, Disk翻译学习DRAM部分(二) DRAM 的发展史 阅读详情

相关推荐

nnDetection复现Luna16 附模型

淘论文发现nnDetection框架对肺结节的检测效果挺好,便跑了跑复现了下, 作者诚不欺人,确实挺好, 并附上我依据文档训练的模型。

HeavenWalker 2598

二叉树的堂兄弟节点

在二叉树中,根节点位于深度0处,每个深度为k的节点的子节点位于深度k+1处。如果二叉树的两个节点深度相同,但,则它们是一对堂兄弟节点。我们给出了具有唯一值的二叉树的根节点root,以及树中两个不同节点的值x和y。只有与值x和y对应的节点是堂兄弟节点时,才返回true。否则,返回false。

qq_64580912的博客 1442

数十个锂电池充放电电路,锂电池充放电芯片

关乎锂电池供电的产品,在锂电池上,需要三个电路系统:1,锂电池保护电路,2,锂电池充电电路,3,锂电池输出电路。 内容目录: 单节的锂电池保护电路单节为3.7V锂电池(也叫4.2V)和3.8V锂电池(也叫4.35V) 单节的锂电池充电电路即锂电池保护板 单节的锂电池输出电路锂电池转换稳压输出为:1.2V,3.3V,5V,12V等等 两节的锂电池保护电路两节串联7.4V锂电池(也叫8.4V) 两节的锂电池充电电路即两节锂电池保护板 两节...

kuakewei123的博客 1万+

leetcode 993. Cousins in Binary Tree(python)

描述 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,

王大呀呀的博客 459

详细推导波特图增益和相位曲线

文章来源:https://mp.weixin.qq.com/s/UCy9mRRok5Hc9qHq3qde5g 今天这篇文章想把近段时间关于波特图方面学习的内容整理一下。波特图将会是梳理闭环控制这个系列的开始。目前的计划是,以无源器件为基础,然后结合运放,再过渡到开关电源的环路控制方面。如果对这方面感兴趣的朋友,可以持续一起学习起来,目标就是掌握开关电源的闭环控制。 1. 什么是波特图? 波特图最常见的应用是在线性非时变的系统中,用于对传递函数的增益和相位进行分析,从而判断出系统随频率的响应是否稳定。因此,波

ltqdxl的博客 2万+

Windows下用Caddy一键搞定LiveKit本地HTTPS部署(含自签名证书避坑指南)

本文详细介绍了在Windows本地开发环境中,如何利用Caddy服务器一键部署支持HTTPS和WSS的LiveKit实时通信服务。文章重点解决了自签名证书的生成与配置难题,提供了完整的避坑指南和防火墙设置,帮助开发者快速搭建安全的WebRTC测试环境,实现局域网内的实时音视频互动。

weixin_29274969的博客 586

【DFS专题】-LeetCode-993. 二叉树的堂兄弟节点

993. 二叉树的堂兄弟节点 提示: 二叉树的节点数介于 2 到 100 之间。 每个节点的值都是唯一的、范围为 1 到 100 的整数。 DFS 思路 🤔 题意转换:其实是让我们判断 xxx、yyy 节点的深度是否相等,且判断 xxx、yyy 的父节点是不是同一个节点 使用 boolean dfs(TreeNode root, int target, int deepth) 来求:求节点值为 targettargettarget 节点的深度(自上而下)、及其父节点 ; 若当前节点 root

weixin_56915683的博客 234

哨兵一号数据snap预处理_利用SNAP软件进行Sentinel-1A卫星微波影像的预处理

利用SNAP软件对雷达影像进行预处理,主要包括热噪声去除、轨道文件校正、辐射定标、滤波校正、多普勒地形校正,最终获得入射角和后向散射信息。数据:本次实验所用数据为哨兵一号(Sentinel-1A)干涉宽幅模式(Interferometric Wideswath,IW)下经过多视处理和地距转换的GRD格式产品一般处理流程如下:0 SNAP软件安装软件安装:安装成功后打开SNAP后如图所示:1 数据...

weixin_30000407的博客 1万+

LeetCode知识点总结 - 993

LeetCode 993. Cousins in Binary Tree 考点 难度 Tree Easy 题目 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 cou

m0_59773145的博客 265

DDR内存条选购避坑指南:单Rank vs 双Rank性能实测对比(附2024年颗粒推荐)

本文深入解析了内存条中单Rank与双Rank设计的原理与性能差异。通过实战测试对比,揭示了双Rank内存在高负载场景(如3D渲染、视频剪辑)中凭借Rank Interleaving技术带来的显著性能优势,并提供了2024年针对不同用户需求的DDR4/DDR5内存选购策略与避坑指南。

ik678901的博客 1148

ArcMap新手必看:5分钟搞定面要素的四至信息提取(附字段重命名技巧)

本文为ArcMap新手提供了快速提取面要素四至信息的详细教程,包括数据准备、坐标系选择、批量处理技巧及字段重命名优化方案。通过实战步骤和Python脚本示例,帮助用户高效完成GIS数据处理任务,特别适合行政区划数据分析和报告生成。

weixin_29266007的博客 389

leetcode 993. Cousins in Binary Tree (二叉树中的堂兄弟)

题目要求 给定二叉树中的两个点,判断这两个点是不是堂兄弟的关系。 所谓堂兄弟就是:深度一样,来自于不同的父节点。 看两个例子 解题思路 本道题使用BFS层序遍历的思想实际不难想到,但是真正操作起来的难点在于:如何判断目标点来自不同的父母,所以根据题中的说明和难点,我们主要完成两件事: 1、记录两个目标点的深度,用来判断是不是在同一层。 2、记录两个目标点的父节点,如果两个点来自同一层,看看他...

爱喝舒化奶的博客 345

基于V7-690T FPGA纯逻辑实现NVMe SSD盘的读写(不使用软核)

a.NVMe的Admin CQ与Admin SQ命令放在Host内存中;因此SQ的64B要用FPGA的DDR或开一个bram空间存放,同理NVME写到HOST的CQ命令也需要存放在FPGA的DDR或一个bram空间,host收到NVME传来的MSI/MSI-X中断后,去CQ存放空间取CQ指令;b. 发送identify命令后,需要发送tial doorbell通知NVME;(发送CNS01h获取4096字节的固件信息等;发送CNS02h获取1024字节的namaspace list)

宝沐熙的博客 839

LeetCode 993. Cousins in Binary Tree

LeetCode 993. Cousins in Binary Tree 993.Cousins in Binary Tree In a binary tree, the root node is at depth0, and children of each depthknode are at depthk+1. Tw...

豆子 357

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

【LeetCode】993. Cousins in Binary Tree 解题报告(C++ & python)

作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录题目描述题目大意解题方法DFSBFS日期 题目地址:https://leetcode.com/problems/cousins-in-binary-tree/ 题目描述 In a binary tree, the root node is at depth 0, and child...

负雪明烛 2832

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

LeetCode993.Cousins in Binary Tree(二叉树的堂兄弟节点 )

993.Cousins in Binary Tree(二叉树的堂兄弟节点 )DescriptionDifficulty: easyExample 1:Example 2:Example 3:Note:分析参考代码 Description In a binary tree, the root node is at depth 0, and children of each depth k node ...

red_tongue的博客 466

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

Leetcode 993. Cousins in Binary Tree

Leetcode 993. Cousins in Binary Tree 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 dep...

大洋深处 601

993. Cousins in Binary Tree*

993. Cousins in Binary Tree* https://leetcode.com/problems/cousins-in-binary-tree/ 题目描述 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 ...

珍妮的选择的博客 386

[leetcode]993. Cousins in Binary Tree(Python)

[leetcode]993. Cousins in Binary Tree题目描述题目理解解题思路DFSBFSTime 题目描述 Category:Easy Tree 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 b...

La_Ragazza的博客 608

【Leetcode】993. Cousins in Binary Tree

题目地址: https://leetcode.com/problems/cousins-in-binary-tree/ 给定一棵二叉树,其值两两不同。再给定两个数xxx和yyy,问这两个数对应的节点是否是cousin。cousin的意思是处于同一深度但父亲节点不同。 可以用BFS,在将某个节点左右孩子入队时判断一下是否是xxx和yyy。如果是则直接返回false,否则将这一行的数全加入一个哈希表,...

数学、算法爱好者的博客 275

Leetcode993 Cousins in Binary Tree解决方案

Leetcode993 Cousins in Binary Tree 题目描述 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

初七的博客 154

leetcode 993. 二叉树的堂兄弟节点(Cousins in Binary Tree)

目录 题目描述: 示例 1: 示例 2: 示例 3: 解法: 题目描述: 在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。 如果二叉树的两个节点深度相同,但父节点不同,则它们是一对堂兄弟节点。 我们给出了具有唯一...

weixin_30410999的博客 196

Leetcode学习笔记:#993. Cousins in Binary Tree

Leetcode学习笔记:#993. Cousins in Binary Tree 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 sam...

ccystewart的博客 308

993. Cousins in Binary Tree

/** * 993. Cousins in Binary Tree * https://leetcode.com/problems/cousins-in-binary-tree/description/ * two nodes in the binary tree are the cousins if they have same depth,but have different ...

weixin_34174105的博客 158

(Java)leetcode-993 Cousins in Binary Tree (二叉树的堂兄弟节点)

涉及二叉树深度,那就上经典BFS吧!

不思量 284

广度优先搜索 leetcode-993-cousins-in-binary-tree​​​​​​​

leetcode-993-cousins-in-binary-tree 题意:判断两个节点是否是相同深度且不同父亲(堂兄弟姐妹) bfs,将节点和深度绑定为pair加入队列,记录目标节点的深度和父亲 遍历完之后判断即可 /** * Definition for a binary tree node. * struct TreeNode { * int val; * ...

Ostrichcrab的博客 233
上一篇: LeetCode.997-找到镇法官(Find the Town Judge)
下一篇: LeetCode.1002-寻找共有字符(Find Common Characters)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址