101. 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.

Subscribe to see which companies asked this question

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public boolean isSymmetric(TreeNode root) {
12         if(root == null) return true;
13         return judge(root.left,root.right);
14     } 
15     public boolean judge(TreeNode left, TreeNode right){
16         if(left == null && right == null) return true;
17         if((left == null && right != null) || (left != null && right == null)) return false;
18         return judge(left.left,right.right) && judge(left.right,right.left) && left.val == right.val;
19     }
20 }

 

posted @ 2016-05-02 21:21  Miller1991  阅读(127)  评论(0编辑  收藏  举报