示例 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:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isCousins(self, root: 'TreeNode', x: 'int', y: 'int') -> 'bool':
stack = [root]
while stack:
all = []
for i in range(len(stack)):
node, a, b = stack.pop(0), 0, 0
if node.left:
a = node.left.val
all.append(a)
stack.append(node.left)
if node.right:
b = node.right.val
all.append(b)
stack.append(node.right)
if (x == a and y == b) or (x == b and y == a):
return False
if x in all and y in all:
return True
return False
DFS:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isCousins(self, root: 'TreeNode', x: 'int', y: 'int') -> 'bool':
depth_dict, father_dict = {}, {}
def dfs(node, father=None):
if node:
depth_dict[node.val] = 1+depth_dict[father.val] if father else 0
father_dict[node.val] = father
dfs(node.left, node)
dfs(node.right, node)
dfs(root)
return x in depth_dict and y in depth_dict and\
depth_dict[x] == depth_dict[y] and father_dict[x] != father_dict[y]