Tutorialspoint
Problem
Solution
Submissions

Symmetric Tree Check

Certification: Basic Level Accuracy: 100% Submissions: 1 Points: 8

Write a Java program to check if a binary tree is symmetric around its center (i.e., mirror of itself). A binary tree is symmetric if the left subtree is a mirror reflection of the right subtree.

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

    Symmetric Tree Check With The Center Symmetric

    • The tree is symmetric around its center.
Example 2
  • Input: root = [1,2,2,null,3,null,3]
  • Output: false
  • Explanation:

    Symmetric Tree Check With Not Symmetricity

    • The tree is not symmetric.
Constraints
  • The number of nodes in the tree is in the range [1, 1000].
  • -100 ≤ Node.val ≤ 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.
RecursionTreeEYPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a recursive approach to check if two subtrees are mirrors of each other.
  • Two trees are a mirror reflection if: - Their root values are the same. - The left subtree of one tree is a mirror of the right subtree of the other.
  • Check if the root's left and right subtrees are mirrors of each other.
  • Handle base cases like empty trees or single-node trees.

Steps to solve by this approach:

 Step 1: Check if the root is null. If so, return true (an empty tree is symmetric).
 Step 2: Create a helper function isMirror() to check if two subtrees are mirrors of each other.
 Step 3: In isMirror(), if both nodes are null, return true.
 Step 4: If one node is null and the other is not, return false.
 Step 5: Check if the current nodes have the same value.
 Step 6: Recursively check if left.left is a mirror of right.right and left.right is a mirror of right.left.
 Step 7: Return the result of the mirror check for the root's left and right subtrees.

Submitted Code :