码迷,mamicode.com
首页 > 其他好文 > 详细

Symmetric Tree

时间:2016-03-16 09:30:47      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

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

递归 check左子树和右子树是否为Symmetric Tree 。

 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 || root.left == null && root.right == null) {
13             return true;
14         }
15         return helper(root.left, root.right);
16         
17     }
18     private boolean helper(TreeNode root1, TreeNode root2) {
19         if (root1 == null) {
20             return root2 == null;
21         }
22         if (root2 == null) {
23             return root1 == null;
24         }
25         if (root1.val != root2.val) {
26             return false;
27         }
28         return helper(root1.right, root2.left) && helper(root1.left, root2.right);
29     }
30 }

 

Symmetric Tree

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5282027.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!