easy Symmetric Tree
Problem Statement
Given the root of a binary tree, return true if the tree is symmetric, meaning it is a mirror image of itself. Otherwise, return false.
A tree is considered symmetric if the left subtree is a mirror reflection of the right subtree.
Examples
Example 1:
- Input: root =
[1,5,5,3,4,4,3]
- Expected Output:
true - Justification: The tree is symmetric because the left subtree mirrors the right subtree at every level.
Example 2:
- Input: root =
[1,5,5,null,3,null,3]
- Expected Output:
false - Justification: The tree is not symmetric because the left and right subtrees do not match in structure or values.
Example 3:
- Input: root =
[1,2,2,null,3,3,null]
- Expected Output:
true - Justification: The tree is symmetric because the left and right subtrees are mirror images in terms of structure and values.
Constraints:
- The number of nodes in the tree is in the range [1, 1000].
- -100 <= Node.val <= 100
Try it yourself
Try solving this question here:
✅ Solution Symmetric Tree
Problem Statement
Given the root of a binary tree, return true if the tree is symmetric, meaning it is a mirror image of itself. Otherwise, return false.
A tree is considered symmetric if the left subtree is a mirror reflection of the right subtree.
Examples
Example 1:
- Input: root =
[1,5,5,3,4,4,3]
- Expected Output:
true - Justification: The tree is symmetric because the left subtree mirrors the right subtree at every level.
Example 2:
- Input: root =
[1,5,5,null,3,null,3]
- Expected Output:
false - Justification: The tree is not symmetric because the left and right subtrees do not match in structure or values.
Example 3:
- Input: root =
[1,2,2,null,3,3,null]
- Expected Output:
true - Justification: The tree is symmetric because the left and right subtrees are mirror images in terms of structure and values.
Constraints:
- The number of nodes in the tree is in the range [1, 1000].
- -100 <= Node.val <= 100
Solution
To solve this problem, the goal is to check whether a binary tree is symmetric. A tree is symmetric if the left and right subtrees of the root are mirror images of each other. To achieve this, the recursive approach known as Depth First Search (DFS) is used to compare the left and right subtrees simultaneously.
The approach begins by checking whether the tree is symmetric starting from the root. A helper method, isMirror, is used to compare two nodes (starting with the root and itself). This method ensures that:
- Both nodes are
null(in which case, they are considered mirrors). - One node is
nulland the other is not (which means the tree is not symmetric). - Both nodes have the same value, and the left subtree of one node is compared to the right subtree of the other.
This approach ensures that every corresponding node in the left and right subtrees are compared in a mirror fashion. By checking these conditions at every step, the algorithm confirms if the tree is symmetric or not.
Step-by-Step Algorithm
-
Call the helper method
isMirror(TreeNode t1, TreeNode t2):- Pass the root node twice to the
isMirrormethod to compare the left and right subtrees. - We begin by checking whether both
t1andt2arenull.
- Pass the root node twice to the
-
Handle null nodes:
- If both nodes are
null, returntruebecause twonullnodes are mirrors of each other. - If one node is
nulland the other is not, returnfalsebecause they are not mirrors.
- If both nodes are
-
Compare the values of the nodes:
- If neither node is
null, compare their values (t1.val == t2.val). - If the values are not equal, return
falsebecause the tree is not symmetric. - If the values are equal, continue to the next step.
- If neither node is
-
Recursive comparison:
- Check the left subtree of
t1with the right subtree oft2by recursively callingisMirror(t1.left, t2.right). - Simultaneously, check the right subtree of
t1with the left subtree oft2by recursively callingisMirror(t1.right, t2.left).
- Check the left subtree of
-
Return the result:
- Both recursive calls must return
truefor the current pair of nodes to be considered mirrors. If both aretrue, the current nodes are mirrors. Otherwise, returnfalse.
- Both recursive calls must return
Algorithm Walkthrough
Input: [1,5,5,3,4,4,3]
-
Initial Step:
- The
isSymmetric()method is called with the root node of the tree (value1).
- The
-
First Call to
isMirror():- The
isMirror()method is called with botht1andt2pointing to the root node (value1). - Since
t1.val == t2.val(both have value1), we move forward to check their subtrees.
- The
-
Check the Left and Right Subtrees:
- Now,
isMirror(t1.left, t2.right)is called to compare the left subtree oft1and the right subtree oft2. - At the same time,
isMirror(t1.right, t2.left)is called to compare the right subtree oft1and the left subtree oft2. - Both pairs have nodes with value
5. Since5 == 5, we move deeper into their subtrees.
- Now,
-
Second Level: Compare Subtrees:
- Next,
isMirror(t1.left.left, t2.right.right)is called to compare the left child oft1.left(value3) with the right child oft2.right(value3). - Also,
isMirror(t1.left.right, t2.right.left)is called to compare the right child oft1.left(value4) with the left child oft2.right(value4). - Both comparisons return
truebecause3 == 3and4 == 4.
- Next,
-
Handle the Leaf Nodes:
- At this point, the algorithm reaches the leaf nodes (
nullvalues). - The
isMirror(null, null)calls check these and returntrue, since both sides arenull.
- At this point, the algorithm reaches the leaf nodes (
-
Return the Result:
- As all recursive calls at each level have returned
true, the algorithm concludes that the tree is symmetric. - The
isSymmetric()method returnstrue, confirming that the tree[1,5,5,3,4,4,3]is indeed symmetric.
- As all recursive calls at each level have returned
Code
// Definition for a binary tree node
// class TreeNode {
// int val;
// TreeNode left;
// TreeNode right;
// // Constructor to initialize the node
// TreeNode(int val) {
// this.val = val;
// this.left = null;
// this.right = null;
// }
// }
public class Solution {
public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
private boolean isMirror(TreeNode t1, TreeNode t2) {
// If both nodes are null, they are mirrors
if (t1 == null && t2 == null) return true;
// If only one of them is null, they are not mirrors
if (t1 == null || t2 == null) return false;
// Two nodes are mirrors if:
// 1. Their values are equal
// 2. The left subtree of one is a mirror of the right subtree of the other
return (t1.val == t2.val)
&& isMirror(t1.left, t2.right)
&& isMirror(t1.right, t2.left);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
// Define left subtree
root.left = new TreeNode(5);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(4);
// Define right subtree (mirrored)
root.right = new TreeNode(5);
root.right.left = new TreeNode(4);
root.right.right = new TreeNode(3);
// Create an instance of the solution class
Solution solution = new Solution();
// Test if the tree is symmetric
boolean result = solution.isSymmetric(root);
// Output the result
System.out.println("Is the tree symmetric? " + result); // Expected: true
}
}
Complexity Analysis
Time Complexity
The isMirror method recursively checks every node in the tree to determine whether the tree is symmetric. Each node is visited once, meaning that for n nodes, the algorithm runs in
Space Complexity
The space complexity is determined by the recursion stack. In the worst case (a skewed tree), the depth of the recursion could be n, leading to a space complexity of
🤖 Don't fully get this? Learn it with Claude
Stuck on Symmetric Tree? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Symmetric Tree** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Symmetric Tree** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Symmetric Tree**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Symmetric Tree**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.