Symmetric Tree
LeetCode 101 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:

Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:

Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
- The number of nodes in the tree is in the range `[1, 1000]`.
- `-100 <= Node.val <= 100`
Follow up: Could you solve it both recursively and iteratively?
Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Approachβ
Tree DFSβ
Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β go right β combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.
Path problems, subtree properties, tree structure manipulation.
Tree BFS (Level-Order)β
Use a queue to process the tree level by level. At each level, process all nodes in the queue, then add their children. Track the level size to know when one level ends and the next begins.
Level-order traversal, level-based aggregation, right/left side view.
Solutionsβ
Solution 1: C# (Best: 112 ms)β
| Metric | Value |
|---|---|
| Runtime | 112 ms |
| Memory | N/A |
| Date | 2018-05-03 |
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public bool IsSymmetric(TreeNode root) {
if(root==null) return true;
return IsSymmetric(root.left, root.right);
}
private bool IsSymmetric(TreeNode left, TreeNode right)
{
if(left==null && right==null) return true;
if(left?.val==right?.val)
{
return IsSymmetric(left.left, right.right) && IsSymmetric(left.right, right.left);
}
return false;
}
}
π 1 more C# submission(s)
Submission (2017-12-21) β 185 ms, N/Aβ
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public bool IsSymmetric(TreeNode root) {
return root==null || IsSymmetric(root.left, root.right);
}
private static bool IsSymmetric(TreeNode left, TreeNode right)
{
if (left != null && right != null)
{
return left.val == right.val
&& IsSymmetric(left.left, right.right)
&& IsSymmetric(left.right, right.left);
}
else if ((left == null && right != null) || (left != null && right == null))
{
return false;
}
return true;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Tree Traversal | $O(n)$ | $O(h)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Consider: "What information do I need from each subtree?" β this defines your recursive return value.