该题解使用了深度优先搜索(DFS)来查找二叉树中的两个节点x和y。通过递归地遍历整个树,它记录下每个节点的父节点和深度。一旦找到与x或y值匹配的节点,它将记录该节点的父节点和深度。最终,如果x和y的深度相同但父节点不同,说明它们是堂兄弟节点,返回true;否则返回false。
时间复杂度: O(n)
空间复杂度: O(n)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
x_parent, x_depth, x_found = None, None, False
y_parent, y_depth, y_found = None, None, False
def dfs(node:TreeNode, depth:int, parent:TreeNode):
if not node:
return
nonlocal x_parent, y_parent, x_depth, y_depth, x_found, y_found
if node.val == x:
x_parent, x_depth, x_found = parent, depth, True
elif node.val == y:
y_parent, y_depth, y_found = parent, depth, True
if x_found and y_found:
return
dfs(node.left, depth+1, node)
if x_found and y_found:
return
dfs(node.right, depth+1, node)
dfs(root, 0, None)
return x_depth == y_depth and x_parent != y_parent