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

给IC设计新人的Tessent Scan入门指南:从RTL到ATPG的完整DFT流程解析 本文为IC设计新手提供Tessent Scan的完整DFT流程指南,从RTL代码检查到ATPG测试向量生成,详细解析扫描链配置、插入及验证的关键步骤。通过实战案例和工具命令示例,帮助工程师快速掌握Tessent工具链的应用技巧,提升芯片可测试性设计的效率和质量。 阅读详情

这是悦乐书的第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+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

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

二十一、CANdelaStudio深入-SPRMIB的配置 本专栏将由浅入深的展开诊断实际开发与测试的数据库编辑,包含大量实际开发过程中的步骤、使用技巧与少量对Autosar标准的解读。希望能对大家有所帮助,与大家共同成长,早日成为一名车载诊断、通信全栈工程师。 本文介绍CANdelaStudio的肯定响应抑制位配置,欢迎各位朋友订阅、评论,可以提出宝贵意见,以持续输出更好的作品,同时会根据评论、私信不定期更新文章内容,以及专栏目录。订阅该专栏的朋友可私信小编免费答疑解惑(^U^)ノ~YO CANdelaStudio-从入门到深入目录 文章目录CANdelaStu 阅读详情

相关推荐

jmeter问题系列:Begin size 0 is not equal to fixed size 5

Begin size 0 is not equal to fixed size 5 ,问题的解决

雨水的早晨的博客 2415

二叉树的堂兄弟节点

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

qq_64580912的博客 1442

Upload Symbols Failed:The archive did not include a dSYM for the LiveKitWebRTC.framework with the UU

你需要从源码构建 LiveKitWebRTC,而不是使用 CocoaPods 安装的预编译 .xcframework。Step 2: 修改 Podfile 使用本地路径引用(不是从源下载的 xcframework)方法 :强制从源码构建 LiveKitWebRTC.framework(推荐)这样它就会编译 WebRTC 并带上正确 UUID 的 dSYM。替换路径为你 clone 下来的 LiveKit 源码位置。Step 1: 克隆源码仓库。

baidu_40537062的博客 2138

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,

王大呀呀的博客 455

如何利用Arcgis进行地统计学分析(三):空间插值方法选择与优化

本文深入探讨了在Arcgis中进行地统计学分析时,如何根据探索性数据分析(EDA)结果科学选择与优化空间插值方法。文章对比了IDW、RBF、克里金等主流方法的适用场景与核心参数,并通过实战案例详解了从数据诊断到模型调优的完整流程,强调结合半变异函数与趋势分析进行“对症下药”,以提升插值结果的精度与可靠性。

weixin_29281915的博客 121

基于FPGA的时间数字转换(TDC)设计(五:基于Carry4的高精度TDC设计)

基于FPGA的时间数字转换(TDC)设计,此为第五篇:基于Carry4的高精度TDC设计。提供工程文件及MATLAB测试分析代码

sdau2005的博客 8808

【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

番外篇 | 关于YOLO11算法的改进点总结

关于YOLO11算法的改进点总结。🌈

小哥谈 2315

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

168、运动控制中的标定:编码器零点标定

文章摘要 运动控制系统中的编码器零点标定是确保精确控制的关键基础步骤。文章通过实际案例说明,即使0.3度的零点偏移也会导致电机异常抖动。详细介绍了三种标定方法:反电动势法(需示波器)、电流注入法(适合量产)和霍尔传感器法(粗标定),并指出常见陷阱如忽略极对数、Z脉冲重复性问题和温度漂移。提供了基于STM32的嵌入式实现代码片段,强调标定后的静态、动态和负载验证的重要性。作者建议量产产品设置自动标定工位,研发样机采用更精确的方法,并强调标定数据应与电机序列号绑定。

m0_50546716的博客 141

Android 人像分割实战:OpenCV+YOLOv8+NCNN 三库联动(附 GPU 加速 / 内存优化全方案)

本文详细介绍了在Android项目中集成OpenCV+YOLOv8+NCNN实现实时人像分割的技术方案。主要内容包括:项目环境搭建(配置NDK、添加Native模块)、核心库文件集成(OpenCV、NCNN、YOLOv8模型)、JNI接口设计与实现(Kotlin层调用C++算法)。通过Camera API获取图像数据,使用YOLOv8进行人体检测,结合NCNN高性能推理框架实现人像分割处理,最终将原始画面与分割结果(背景透明)同时显示在Android界面上。该项目采用多技术栈协同工作,OpenCV负责图像处

FJN110的博客 236

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

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

爱喝舒化奶的博客 345

从零搭建 C# + YOLO 工业视觉系统:从模型训练到上位机部署(工业级落地)

做工业质检、自动化生产线的同学都懂:一套能用的工业视觉系统,既要“检测准”,又要“界面易操作”,还要“部署稳”。之前帮某电子厂做PCB缺陷检测,一开始用Python+YOLO做检测核心,QT做上位机,结果踩了无数坑:Python推理速度波动大,QT和Python跨语言集成繁琐,数据传递容易卡顿;后来换成C# + YOLO的组合,直接打通了“模型训练-上位机开发-工业部署”全流程——C#的WinForms/WPF开发上位机高效,工业相机SDK支持完善;

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 737

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

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

数学建模模型总结

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

【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...

负雪明烛 2828

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

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

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

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...

大洋深处 600

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,否则将这一行的数全加入一个哈希表,...

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

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的博客 157

(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、付费专栏及课程。

余额充值