
Problem
Solution
Submissions
Symmetric Tree
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to check if a binary tree is symmetric around its center, meaning it is a mirror of itself. A binary tree is symmetric if the left subtree of the root is a mirror reflection of the right subtree of the root.
Example 1
- Input:
- Output: true
- Explanation:
- The left subtree of the root (1) consists of nodes 2, 3, and 4.
- The right subtree of the root (1) consists of nodes 2, 4, and 3.
- The left subtree is a mirror reflection of the right subtree.
- The values match in mirror positions (2-2, 3-3, 4-4).
- Therefore, the tree is symmetric.
- The left subtree of the root (1) consists of nodes 2, 3, and 4.
Example 2
- Input:
- Output: false
- Explanation:
- The left subtree of the root (1) consists of nodes 2 and 3.
- The right subtree of the root (1) consists of nodes 2 and 3.
- In the left subtree, node 3 is the right child of node 2.
- In the right subtree, node 3 is also the right child of node 2.
- In a mirror reflection, node 3 in the right subtree should be the left child of node 2.
- Since this is not the case, the tree is not symmetric.
- The left subtree of the root (1) consists of nodes 2 and 3.
Constraints
- The number of nodes in the tree is in the range [1, 1000].
- The values of nodes are integers in the range [-100, 100].
- Time Complexity: O(n), where n is the number of nodes in the tree.
- Space Complexity: O(h), where h is the height of the tree (due to recursion stack).
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a recursive approach to check if two subtrees are mirror images of each other.
- Start by comparing the left and right subtrees of the root.
- Two subtrees are mirror images if: a. Their root values are the same b. The left subtree of one is a mirror of the right subtree of the other c. The right subtree of one is a mirror of the left subtree of the other
- Handle the base cases properly (e.g., when both nodes are NULL).
- You can also use an iterative approach with a queue or stack if preferred.
- Be careful about the comparison conditions to ensure proper mirroring.
- Consider edge cases like empty trees or trees with only one node.