LeetCode(18)二叉树的堂兄弟节点(简单)

问题描述:

在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。

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

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

只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true 。否则,返回 false。

代码:

class Solution {
// x 的信息
int x;
TreeNode xParent;
int xDepth;
boolean xFound = false;

// y 的信息
int y;
TreeNode yParent;
int yDepth;
boolean yFound = false;

public boolean isCousins(TreeNode root, int x, int y) {
this.x = x;
this.y = y;
dfs(root, 0, null);
return xDepth == yDepth && xParent != yParent;
}

public void dfs(TreeNode node, int depth, TreeNode parent) {
if (node == null) {
return;
}

if (node.val == x) {
xParent = parent;
xDepth = depth;
xFound = true;
} else if (node.val == y) {
yParent = parent;
yDepth = depth;
yFound = true;
}

// 如果两个节点都找到了,就可以提前退出遍历
// 即使不提前退出,对最坏情况下的时间复杂度也不会有影响
if (xFound && yFound) {
return;
}

dfs(node.left, depth + 1, node);

if (xFound && yFound) {
return;
}

dfs(node.right, depth + 1, node);
}
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/cousins-in-binary-tree/solution/er-cha-shu-de-tang-xiong-di-jie-dian-by-mfh2d/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

值得注意的:

 

 两种不同搜索方法。深度搜索和广度搜索 本题解采用深度搜索。

posted @ 2021-05-20 22:04  ash98  阅读(51)  评论(0)    收藏  举报