Same Tree
LeetCode 100 · Easy · solution, intuition & step-by-step walkthrough
Compare roots and recurse in lockstep.
This is how I solved Same Tree (LeetCode 100), an easy problem from the DFS Basics pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Two trees are the same if their roots match and their left subtrees are the same and their right subtrees are the same. Two empty trees are equal; one empty and one not are different.
Approach
- 1
Both None → True; one None → False.
- 2
Values equal and both subtree pairs equal.
How I solved it
Parallel DFSPythonO(n) time · O(h) space
# 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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
def dfs(node1,node2):
if node1==None and node2==None:
return True
if node1==None or node2==None:
return False
return node1.val==node2.val and dfs(node1.left,node2.left) and dfs(node1.right,node2.right)
return dfs(p,q)Same Tree — FAQ
What is the intuition behind Same Tree?
Two trees are the same if their roots match and their left subtrees are the same and their right subtrees are the same. Two empty trees are equal; one empty and one not are different.
How do you solve Same Tree (LeetCode 100)?
1. Both None → True; one None → False. 2. Values equal and both subtree pairs equal.
What is the time and space complexity of Same Tree?
Time: O(n). Space: O(h). (Accepted approach: Parallel DFS.)
What are common mistakes in Same Tree?
Check the None cases before reading .val.