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.

 

 

题意为判断一颗二叉树是不是对称的。

解法是递归,一颗二叉树对称,必须是其左右孩子互相对称,左孩子的左子树对称于右孩子的右子树,左孩子的右子树对称于右孩子的左子树。

 

 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     
12     private boolean isChildSymmetric(TreeNode root1,TreeNode root2) {
13         if (root1==null && root2==null) {
14             return true;
15         }
16         if (root1==null || root2==null) {
17             return false;
18         }
19         if (root1.val==root2.val) {
20             if (isChildSymmetric(root1.left, root2.right) && isChildSymmetric(root1.right, root2.left)) {
21                 return true;
22             } else {
23                 return false;
24             }
25         } else {
26             return false;
27         }
28     }
29     
30     
31     public boolean isSymmetric(TreeNode root) {
32         if (root == null) {
33             return true;
34         }
35         return isChildSymmetric(root.left, root.right);
36     }
37 }

 

posted @ 2014-10-02 08:24  birdhack  阅读(137)  评论(0编辑  收藏  举报