Monday, November 2, 2015

[leetcode] Symmetric Tree

通过preorder产生一个list, 含有String = val + "," + level
然后判断是否对称就好了
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Solution {
    ArrayList<String> list = new ArrayList<String>();
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        inOrder(root, 0);
        if (list.size() % 2 == 0) return false;
        int i = 0;
        int j = list.size()-1;
        while (i != j){
         if (!list.get(i).equals(list.get(j))){
          return false;
         }
         i++;
         j--;
        }
        return true;
    }

    private void inOrder(TreeNode root, int level){
     if (root == null) return;
     inOrder(root.left, level+1);
     String temp = root.val+","+level;
     list.add(temp);
     inOrder(root.right, level+1);
    }
}

另一种方法... 每次都没有反应过来。。。其实细心点就会发现要将left.left 和right.right 对比还有left.right和right.left对比

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * 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 check(root.left, root.right);
    }

    boolean check(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 check(left.left, right.right)&&check(left.right, right.left);
    }
}

No comments:

Post a Comment