Symmetric Tree
LeetCode 101 · Easy · solution, intuition & step-by-step walkthrough
Mirror check: outer with outer, inner with inner.
This is how I solved Symmetric Tree (LeetCode 101), 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
A tree is symmetric if its left subtree is a mirror of its right. Compare two nodes at a time: their values must match, and the outer pair (left.left, right.right) and inner pair (left.right, right.left) must also be mirrors.
Approach
- 1
dfs(left, right): both None → True; one None → False.
- 2
Values equal, dfs(left.left, right.right), dfs(left.right, right.left).
How I solved it
Mirror 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
def dfs(left,right):
if left==None and right==None:
return True
if left==None or right==None:
return False
return left.val==right.val and dfs(left.left,right.right) and dfs(left.right,right.left)
return dfs(root.left,root.right)Symmetric Tree — FAQ
What is the intuition behind Symmetric Tree?
A tree is symmetric if its left subtree is a mirror of its right. Compare two nodes at a time: their values must match, and the outer pair (left.left, right.right) and inner pair (left.right, right.left) must also be mirrors.
How do you solve Symmetric Tree (LeetCode 101)?
1. dfs(left, right): both None → True; one None → False. 2. Values equal, dfs(left.left, right.right), dfs(left.right, right.left).
What is the time and space complexity of Symmetric Tree?
Time: O(n). Space: O(h). (Accepted approach: Mirror DFS.)
What are common mistakes in Symmetric Tree?
Compare cross-wise, not left-with-left.