Symmetric Tree

Symmetric Tree

Sergei Golitsyn

https://leetcode.com/problems/symmetric-tree/


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

Solution

The main point here is to understand what we should do. Based on the explanation, we understand that a symmetric tree is a mirror. That means that the left part is equal to the right part. Is it clear? We should always check the right node in the left subtree and the left in the right subtree. And the same approach for the left node in the left subtree and the right node in the right subtree.

  public boolean isSymmetric(TreeNode root) {
     
    return isSymmetric(root, root);
  }
   
  private boolean isSymmetric(TreeNode left, TreeNode right){
    if (left == null && right == null){
      return true;
    }
    if (left == null || right == null){
      return false;
    }
     
    if (left.val != right.val){
      return false;
    }
     
    return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
  } 


Report Page