#101
Symmetric Tree
EasyTreeDepth-First SearchBreadth-First SearchBinary TreeRecursionTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(h) |
💡
Intuition
Time O(n)Space O(h)
The optimal approach uses a recursive helper function to directly compare the left and right subtrees. This is efficient because it avoids extra space for storing node values and checks symmetry in a single traversal.
⚙️
Algorithm
4 steps- 1Step 1: Create a helper function that takes two nodes as parameters.
- 2Step 2: If both nodes are null, return true (base case).
- 3Step 3: If one node is null and the other is not, return false.
- 4Step 4: Check if the values of both nodes are equal, and recursively check the left and right children in a mirrored fashion.
solution.py17 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8class Solution:
9 def isSymmetric(self, root: TreeNode) -> bool:
10 def isMirror(left, right):
11 if not left and not right:
12 return True
13 if not left or not right:
14 return False
15 return (left.val == right.val) and isMirror(left.left, right.right) and isMirror(left.right, right.left)
16
17 return isMirror(root, root)ℹ
Complexity note: The time complexity is O(n) because we visit each node once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.
- 1Symmetry can be checked directly by comparing nodes
- 2Recursion can simplify tree traversal problems
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.