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

输入:root = [1,2,3,null,4], x = 2, y = 3 输出:false
提示:
- 二叉树的节点数介于
2到100之间。 - 每个节点的值都是唯一的、范围为
1到100的整数。
思路:基本的层次遍历
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: int
:type y: int
:rtype: bool
"""
if x==root.val or y==root.val:
return False
tmp = [root]
while tmp:
l = []
xflag = False
yflag = False
vals = []
for i in tmp:
if i.left and i.right:
if x in [i.left.val, i.right.val] and y in [i.left.val, i.right.val]:
return False
if i.left:
l.append(i.left)
if i.right:
l.append(i.right)
if i.val == x:
if yflag == True:
return True
else:
xflag = True
if i.val == y:
if xflag == True:
return True
else:
yflag = True
tmp = l
return False
本文介绍了一种通过层次遍历来判断二叉树中两个节点是否为堂兄弟节点的方法。堂兄弟节点定义为处于同一深度但拥有不同父节点的节点。文章通过示例详细解释了这一概念,并提供了具体的实现思路。
404

被折叠的 条评论
为什么被折叠?



