101. Symmetric Tree

Problem:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
    1
   / \
  2   2
 / \ / \
3  4 4  3
But the following [1,2,2,null,3,null,3] is not:
    1
   / \
  2   2
   \   \
   3    3
Analysis:
如果当前对比的node1 和node 2相等,要符合symmetric tree我们需要比较node1.left == node2.right && node1.right == node2.left.
Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    public boolean isSymmetric(TreeNode root) {
        return root == null || helper(root.left, root.right);
    }
    
    private boolean helper(TreeNode left, TreeNode right) {
        if (left == null && right == null)
            return true;
        if ((left != null && right == null) || (left == null && right != null) || left.val != right.val)
            return false;
        return helper(left.right, right.left) && helper(left.left, right.right);
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array