LeetCode 每日一题 :993. 二叉树的堂兄弟节点

编程入门 行业动态 更新时间:2024-10-11 13:20:17

LeetCode 每日一题 :993. 二叉树的<a href=https://www.elefans.com/category/jswz/34/1753664.html style=堂兄弟节点"/>

LeetCode 每日一题 :993. 二叉树的堂兄弟节点

LeetCode 每日一题 :993. 二叉树的堂兄弟节点

原题链接

分析:

判断两个节点是否为堂兄弟节点就需要判断它们的父节点是否不同以及它们的高度是否相同。那么问题就变为了求两个节点的父节点及其高度。使用深度优先遍历这棵树即可。

代码
/*** 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 {int x;TreeNode xParent;int xDepth;int y;TreeNode yParent;int yDepth;public boolean isCousins(TreeNode root, int x, int y) {this.x = x;this.y = y;dfs(root, null, 0);return xDepth == yDepth && xParent != yParent;}public void dfs(TreeNode root, TreeNode parent, int depth) {if (root == null) {return ;}if (root.val == this.x) {this.xDepth = depth;this.xParent = parent;}if (root.val == this.y) {this.yDepth = depth;this.yParent = parent;}dfs(root.left, root, depth + 1);dfs(root.right, root, depth + 1);}
}

更多推荐

LeetCode 每日一题 :993. 二叉树的堂兄弟节点

本文发布于:2024-02-07 05:52:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1753392.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:堂兄弟   节点   二叉树   LeetCode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!