Bird
Raised Fist0
DSA C++programming~15 mins

Check if Two Trees are Symmetric in DSA C++ - Deep Dive

Choose your learning style10 modes available
Overview - Check if Two Trees are Symmetric
What is it?
Checking if two trees are symmetric means verifying if one tree is a mirror image of the other. This involves comparing nodes in a way that the left subtree of one tree matches the right subtree of the other, and vice versa. It helps us understand if two tree structures are balanced in a mirrored way. This concept is important in many tree-related problems and algorithms.
Why it matters
Without this concept, we would struggle to quickly determine if two trees have a mirrored structure, which is useful in tasks like validating symmetric data, graphical representations, or balancing operations. It saves time and effort by providing a clear method to compare tree shapes and values. In real life, symmetry often means balance and harmony, and this check helps computers find that balance in tree data.
Where it fits
Before learning this, you should understand basic tree structures, especially binary trees, and how to traverse them. After this, you can explore more complex tree problems like tree isomorphism, subtree checks, or tree serialization. This topic builds on tree traversal and comparison techniques.
Mental Model
Core Idea
Two trees are symmetric if one is the mirror image of the other, meaning their left and right subtrees match in opposite positions with equal values.
Think of it like...
Imagine two hands facing each other palm to palm. If you fold one hand over the other, every finger lines up perfectly with its opposite. The trees are symmetric if their branches and leaves match like these mirrored fingers.
Tree1:          Tree2 (mirror)
    1                 1
   / \               / \
  2   3             3   2
 /                   \
4                     4

Symmetric because left subtree of Tree1 matches right subtree of Tree2 and vice versa.
Build-Up - 6 Steps
1
FoundationUnderstand Binary Tree Structure
🤔
Concept: Learn what a binary tree is and how nodes connect with left and right children.
A binary tree is a structure where each node has up to two children: left and right. Each node holds a value. For example, a node with value 1 can have a left child with value 2 and a right child with value 3. This structure allows us to organize data hierarchically.
Result
You can visualize and represent trees with nodes and their left and right children.
Understanding the basic tree structure is essential because symmetry depends on comparing these left and right children.
2
FoundationLearn Tree Traversal Basics
🤔
Concept: Explore how to visit nodes in a tree systematically using traversal methods.
Traversal means visiting each node in a tree in a specific order. Common ways are preorder (node, left, right), inorder (left, node, right), and postorder (left, right, node). Traversal helps us access all nodes to compare or process them.
Result
You can write code to visit every node in a tree in a predictable order.
Traversal is the foundation for comparing trees because you need to visit nodes in a way that reveals their structure.
3
IntermediateCompare Two Trees Node-by-Node
🤔Before reading on: Do you think comparing only root nodes is enough to check symmetry? Commit to yes or no.
Concept: Introduce the idea of comparing corresponding nodes in two trees recursively.
To check if two trees are symmetric, start by comparing their root nodes. If roots differ, trees are not symmetric. Then compare the left child of the first tree with the right child of the second tree, and the right child of the first tree with the left child of the second tree. Repeat this process recursively for all nodes.
Result
You can determine if two trees have matching values in mirrored positions.
Knowing that symmetry requires mirrored node comparison, not just matching values, is key to solving the problem.
4
IntermediateImplement Recursive Symmetry Check
🤔Before reading on: Will a simple recursive function that compares left with left and right with right work for symmetry? Commit to yes or no.
Concept: Use recursion to check if two trees are mirror images by comparing opposite children.
Write a function that takes two nodes. If both are null, return true (empty trees are symmetric). If one is null and the other isn't, return false. If values differ, return false. Otherwise, recursively check if left child of first node matches right child of second node and right child of first node matches left child of second node.
Result
A working recursive function that returns true if trees are symmetric, false otherwise.
Understanding the recursive pattern of mirrored comparison unlocks an elegant and efficient solution.
5
AdvancedHandle Edge Cases and Null Nodes
🤔Before reading on: Do you think ignoring null nodes can cause wrong symmetry results? Commit to yes or no.
Concept: Learn to carefully handle cases where nodes are missing on one side but present on the other.
When comparing nodes, if one node is null and the other is not, trees are not symmetric. If both are null, they are symmetric at that position. This prevents false positives where missing branches are overlooked.
Result
The function correctly identifies asymmetry caused by missing nodes.
Handling null nodes properly prevents subtle bugs and ensures the function works for all tree shapes.
6
ExpertOptimize with Iterative Approach Using Queue
🤔Before reading on: Do you think recursion is the only way to check tree symmetry? Commit to yes or no.
Concept: Use an iterative method with a queue to check symmetry without recursion.
Initialize a queue and add the root nodes of both trees. While the queue is not empty, remove two nodes at a time and compare them. If both are null, continue. If one is null or values differ, return false. Add children in mirrored order to the queue: left child of first node with right child of second node, and right child of first node with left child of second node. Continue until queue is empty.
Result
An iterative function that returns true if trees are symmetric, false otherwise, without recursion.
Knowing iterative solutions helps avoid stack overflow in deep trees and shows alternative problem-solving methods.
Under the Hood
The symmetry check works by recursively or iteratively comparing pairs of nodes from two trees in mirrored positions. Each comparison checks if both nodes are null (symmetric), if one is null (not symmetric), or if their values differ (not symmetric). The process continues by comparing the left subtree of one tree with the right subtree of the other, ensuring a mirror structure. This relies on the call stack in recursion or a queue in iteration to keep track of node pairs.
Why designed this way?
This approach was chosen because symmetry inherently involves mirrored positions, which naturally fits recursive or paired comparisons. Alternatives like flattening trees or comparing traversals fail to capture the mirror structure directly. Recursion simplifies the logic by naturally exploring subtrees, while iteration avoids deep call stacks. The design balances clarity, correctness, and efficiency.
Start
  │
  ▼
Compare root nodes
  │
  ├─ If both null -> symmetric here
  ├─ If one null -> not symmetric
  ├─ If values differ -> not symmetric
  │
  ▼
Compare left subtree of Tree1 with right subtree of Tree2
Compare right subtree of Tree1 with left subtree of Tree2
  │
  ▼
Repeat recursively or iteratively until all nodes checked
  │
  ▼
Return true if all pairs symmetric, else false
Myth Busters - 4 Common Misconceptions
Quick: Does comparing preorder traversals of two trees confirm symmetry? Commit yes or no.
Common Belief:If two trees have the same preorder traversal, they are symmetric.
Tap to reveal reality
Reality:Preorder traversal alone does not capture mirror structure; trees can have identical preorder traversals but not be symmetric.
Why it matters:Relying on traversal equality can cause false positives, leading to incorrect symmetry checks.
Quick: Is symmetry the same as equality of two trees? Commit yes or no.
Common Belief:Two trees are symmetric if they are exactly the same (equal).
Tap to reveal reality
Reality:Symmetry means one tree is the mirror image of the other, not necessarily identical in structure or order.
Why it matters:Confusing symmetry with equality causes wrong assumptions and incorrect algorithm design.
Quick: Can ignoring null children during comparison still yield correct symmetry? Commit yes or no.
Common Belief:Null children can be ignored because they don't affect symmetry.
Tap to reveal reality
Reality:Null children must be considered; missing nodes on one side break symmetry.
Why it matters:Ignoring nulls leads to false positives, incorrectly marking asymmetric trees as symmetric.
Quick: Does recursion always guarantee the best performance for symmetry checks? Commit yes or no.
Common Belief:Recursion is always the best way to check tree symmetry.
Tap to reveal reality
Reality:Recursion is clear but can cause stack overflow on deep trees; iterative methods can be safer and more efficient.
Why it matters:Choosing recursion blindly can cause runtime errors in large inputs.
Expert Zone
1
Symmetry checking can be extended to n-ary trees but requires more complex mirrored child comparisons.
2
Iterative solutions require careful ordering of node pairs in the queue to maintain correct mirror comparisons.
3
In some cases, symmetry checks can be combined with subtree hashing to optimize repeated queries.
When NOT to use
Avoid symmetry checks when trees are very large and deep without tail recursion optimization; use iterative methods or limit recursion depth. For non-binary trees, specialized algorithms are needed. If only equality is needed, simpler direct comparison suffices.
Production Patterns
Used in graphical UI frameworks to verify mirrored layouts, in compiler syntax tree optimizations to detect symmetric code patterns, and in network topology checks where mirrored structures imply redundancy or balance.
Connections
Tree Isomorphism
Builds-on
Understanding symmetry helps grasp tree isomorphism, which checks if two trees can be made identical by rearranging children, a more general problem.
Palindrome Checking
Similar pattern
Both symmetry in trees and palindrome checking in strings involve mirrored comparisons from opposite ends, teaching a common approach to mirrored data.
Human Facial Symmetry in Biology
Analogous concept
Studying tree symmetry algorithms can deepen understanding of biological symmetry, showing how mirrored structures are fundamental in nature and design.
Common Pitfalls
#1Ignoring null nodes during comparison
Wrong approach:if (node1->val != node2->val) return false; return isSymmetric(node1->left, node2->right) && isSymmetric(node1->right, node2->left);
Correct approach:if (!node1 && !node2) return true; if (!node1 || !node2) return false; if (node1->val != node2->val) return false; return isSymmetric(node1->left, node2->right) && isSymmetric(node1->right, node2->left);
Root cause:Not checking for null nodes causes the function to access invalid memory or wrongly assume symmetry.
#2Comparing left subtree with left subtree instead of mirrored sides
Wrong approach:return isSymmetric(node1->left, node2->left) && isSymmetric(node1->right, node2->right);
Correct approach:return isSymmetric(node1->left, node2->right) && isSymmetric(node1->right, node2->left);
Root cause:Misunderstanding symmetry as equality rather than mirrored structure.
#3Using recursion without base case for null nodes
Wrong approach:if (node1->val != node2->val) return false; return isSymmetric(node1->left, node2->right) && isSymmetric(node1->right, node2->left);
Correct approach:if (!node1 && !node2) return true; if (!node1 || !node2) return false; if (node1->val != node2->val) return false; return isSymmetric(node1->left, node2->right) && isSymmetric(node1->right, node2->left);
Root cause:Missing base cases leads to runtime errors or infinite recursion.
Key Takeaways
Symmetry in trees means one tree is the mirror image of the other, requiring mirrored node comparisons.
Proper handling of null nodes is essential to avoid incorrect symmetry results.
Recursion naturally fits the symmetry check but iterative methods can be safer for deep trees.
Symmetry checking builds on basic tree traversal and comparison concepts and connects to broader problems like tree isomorphism.
Misunderstanding symmetry as equality or ignoring nulls are common pitfalls that cause bugs.

Practice

(1/5)
1. What does it mean for two binary trees to be symmetric?
easy
A. They have the same root value only.
B. They have the same number of nodes.
C. They are mirror images of each other around their center.
D. They have identical left subtrees only.

Solution

  1. Step 1: Understand symmetry in trees

    Two trees are symmetric if one is the mirror reflection of the other around the center.
  2. Step 2: Compare structure and node values

    Both structure and node values must match in a mirrored way for symmetry.
  3. Final Answer:

    They are mirror images of each other around their center. -> Option C
  4. Quick Check:

    Symmetry means mirror image = A [OK]
Hint: Symmetric trees mirror each other perfectly [OK]
Common Mistakes:
  • Thinking same number of nodes means symmetric
  • Only comparing root values
  • Ignoring structure when checking symmetry
2. Which of the following C++ function signatures correctly represents a function to check if two trees are symmetric?
easy
A. int isSymmetric(TreeNode* root1, TreeNode* root2);
B. bool isSymmetric(TreeNode* root1, TreeNode* root2);
C. void isSymmetric(TreeNode root1, TreeNode root2);
D. bool isSymmetric(TreeNode root1, TreeNode root2);

Solution

  1. Step 1: Identify correct return type

    The function should return a boolean indicating symmetry, so return type is bool.
  2. Step 2: Use pointers for tree nodes

    Tree nodes are usually passed as pointers to avoid copying and to handle null nodes.
  3. Final Answer:

    bool isSymmetric(TreeNode* root1, TreeNode* root2); -> Option B
  4. Quick Check:

    Return bool and use pointers = C [OK]
Hint: Use bool return and pointers for tree nodes [OK]
Common Mistakes:
  • Using void return type
  • Passing nodes by value instead of pointer
  • Using int instead of bool for result
3. What will be the output of the following code snippet?
#include <iostream>

struct TreeNode {
  int val;
  TreeNode* left;
  TreeNode* right;
  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

bool isMirror(TreeNode* t1, TreeNode* t2) {
  if (!t1 && !t2) return true;
  if (!t1 || !t2) return false;
  return (t1->val == t2->val) && isMirror(t1->left, t2->right) && isMirror(t1->right, t2->left);
}

int main() {
  TreeNode* root1 = new TreeNode(1);
  root1->left = new TreeNode(2);
  root1->right = new TreeNode(3);

  TreeNode* root2 = new TreeNode(1);
  root2->left = new TreeNode(3);
  root2->right = new TreeNode(2);

  if (isMirror(root1, root2))
    std::cout << "Symmetric";
  else
    std::cout << "Not Symmetric";
  return 0;
}
medium
A. Symmetric
B. Not Symmetric
C. Compilation Error
D. Runtime Error

Solution

  1. Step 1: Analyze tree structures

    root1 has left=2, right=3; root2 has left=3, right=2, which are mirror images.
  2. Step 2: Trace isMirror function

    Values match and recursive calls check left-right and right-left subtrees, confirming symmetry.
  3. Final Answer:

    Symmetric -> Option A
  4. Quick Check:

    Mirror check returns true = Symmetric [OK]
Hint: Check mirrored node values and subtree positions [OK]
Common Mistakes:
  • Confusing left and right subtree checks
  • Ignoring null node base cases
  • Assuming same structure means symmetric
4. Identify the bug in the following code that checks if two trees are symmetric:
bool isMirror(TreeNode* t1, TreeNode* t2) {
  if (!t1 && !t2) return true;
  if (!t1 || !t2) return false;
  return (t1->val == t2->val) && isMirror(t1->left, t2->left) && isMirror(t1->right, t2->right);
}
medium
A. It uses incorrect return type.
B. It does not check for null nodes.
C. It returns true when both nodes are null.
D. It compares left subtree with left subtree instead of left with right.

Solution

  1. Step 1: Review recursive calls for symmetry

    Symmetry requires comparing left subtree of one tree with right subtree of the other.
  2. Step 2: Identify incorrect subtree comparisons

    The code compares left with left and right with right, which checks for identical trees, not symmetric.
  3. Final Answer:

    It compares left subtree with left subtree instead of left with right. -> Option D
  4. Quick Check:

    Mirror needs left-right swap, code misses it = D [OK]
Hint: Mirror check swaps left and right subtrees [OK]
Common Mistakes:
  • Comparing same side subtrees instead of mirrored sides
  • Ignoring null checks
  • Confusing identical and symmetric trees
5. Given two binary trees, write a function that returns true if they are symmetric around their center. Which approach correctly solves this problem?
hard
A. Use a recursive function that compares left subtree of first tree with right subtree of second tree and vice versa.
B. Traverse both trees in preorder and compare node values in order.
C. Check if both trees have the same number of nodes and same root value.
D. Use a queue to perform level order traversal and compare nodes at each level without mirroring.

Solution

  1. Step 1: Understand symmetry check logic

    Symmetry means one tree is mirror of the other, so compare left subtree of one with right subtree of other recursively.
  2. Step 2: Evaluate other approaches

    Preorder traversal or node count alone do not guarantee symmetry; level order without mirroring misses mirror structure.
  3. Final Answer:

    Use a recursive function that compares left subtree of first tree with right subtree of second tree and vice versa. -> Option A
  4. Quick Check:

    Recursive mirror comparison solves symmetry = A [OK]
Hint: Recursively compare left with right subtree for symmetry [OK]
Common Mistakes:
  • Using simple traversal without mirroring
  • Comparing only node counts or root values
  • Ignoring subtree structure in mirror form
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard