2015年10月7日星期三

#LeetCode# Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
    1
   / \
  2   2
 / \ / \
3  4 4  3
But the following is not:
    1
   / \
  2   2
   \   \
   3    3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

去年用OCaml学算法的时候做过这题,清楚记得当初法语描述是mirror arbre。这次用java做,遇到几个问题,

1. 不仅要考虑左右两子树同时为Null的情况,还要考虑两者不同时为Null的情况
2. 镜面树,是严格对称。第一次写成了left.left==right.left && left.right==right.right 结果Fail我还纳闷了半天

好了,上代码,

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

}

平时的课好好学,还是很有用的。M1的目标就是好好学算法和数学。加油!

没有评论:

发表评论