Question:

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

Note: Bonus points if you could solve it both recursively and iteratively.

Thinking:

  • Method:
    • 递归。
    • 分别检测最左侧和最右侧,然后检测中间的两侧。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        return check(root.left, root.right);
    }
    private static boolean check(TreeNode node1, TreeNode node2){
        if(node1 == null && node2 == null) return true;
        if(node1 == null || node2 == null)
            return false;
        if(node1.val == node2.val) 
            return check(node1.left, node2.right) && check(node1.right, node2.left);
        return false;
    }
}

二刷

这道题还是简单的,直接就写出来了。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        return check(root.left, root.right);
    }
    private boolean check(TreeNode n1, TreeNode n2){
        if(n1 == null && n2 == null) return true;
        else if(n1 == null || n2 == null) return false;
        else{
            if(n1.val != n2.val) return false;
            return check(n1.left, n2.right) && check(n1.right, n2.left);
        }
    }
}