Skip to main content

Symmetric Tree

LeetCode 101 | Difficulty: Easy​

Easy

Problem 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.

When to use

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.

When to use

Level-order traversal, level-based aggregation, right/left side view.


Solutions​

Solution 1: C# (Best: 112 ms)​

MetricValue
Runtime112 ms
MemoryN/A
Date2018-05-03
Solution
/**
* 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​

ApproachTimeSpace
Tree Traversal$O(n)$$O(h)$

Interview Tips​

Key Points
  • 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.