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

Solution:

 1 /**
 2  * Definition for binary tree
 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 check(TreeNode r1, TreeNode r2){
12         if(r1 == null && r2 == null) 
13             return true;
14         if(r1 == null || r2 == null)
15             return false;
16         if(r1.val != r2.val)
17             return false;
18         return check(r1.left, r2.right) && check(r1.right, r2.left);
19     }
20     public boolean isSymmetric(TreeNode root) {
21         // Start typing your Java solution below
22         // DO NOT write main() function
23         if(root == null) return true;
24         return check(root.left, root.right);
25     }
26 }

 


 

 

posted @ 2013-01-28 08:37  cradle  阅读(174)  评论(0编辑  收藏  举报