Skip to main content

Two Trees

100. Same Tree

Explanation

Interactive Visualization

Analysis

def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
def dfs(a, b):
if not a and not b:
return True
if not a or not b:
return False
if a.val != b.val:
return False
return dfs(a.left, b.left) and dfs(a.right, b.right)

return dfs(p, q)

101. Symmetric Tree

Explanation

Analysis

def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def dfs(left, right):
if not right and not left:
return True
if not right or not left:
return False
if left.val != right.val:
return False
return dfs(left.left, right.right) and dfs(left.right, right.left)

return dfs(root, root)

1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree

Explanation

Analysis

def getTargetCopy(
self, original: TreeNode, cloned: TreeNode, target: TreeNode
) -> TreeNode:
def dfs(a, b):
if a and b:
if a == target:
return b
left_result = dfs(a.left, b.left)
right_result = dfs(a.right, b.right)
return left_result or right_result

return dfs(original, cloned)