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

leetcode------Symmetric Tree

时间:2014-12-21 23:18:31      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

标题: Symmetric Tree
通过率: 31.1%
难度: 简单

 

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.

这几天在忙期末考试,实在是抽不出来时间去刷题,今天随便打开了一道,吓尿了,题目都好长啊,我看了半天没有看懂他的解释,我还是按照自己的理解去写吧,写了三道树的题目,我感觉树的题目千篇一律,就是递归后怎么去处理了。看了这道题目,就是判断这个树是不是个完全对称树,我想了下,递归的时候就是就让树同时迭代左右,然后根据对称性,我画一个最简单的图:

技术分享

上图的节点的数字是节点的编号,不是值,把树成左右判断。相当于分成了 2,3 然后就是2的右边要和3的左边相同(即5,6要相同),2的左边要和3的右边相同(即4,7要相同),以此类推,

如果中间有单个空或者值不同就返回false,

直接读递归的代码,能加深理解,具体的代码如下:比较简洁:

 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 isSymmetric(TreeNode root) {
12         if(root==null) return true;
13         return issame( root.left, root.right);
14     }
15     public boolean issame(TreeNode left,TreeNode right){
16         if(left==null&&right==null) return true;
17         if(left!=null &&right==null) return false;
18         if(left==null &&right !=null)return false;
19         if(left.val!=right.val) return false;
20         else 
21         return issame(left.right,right.left)&&issame(left.left,right.right);
22     }
23 }

 

leetcode------Symmetric Tree

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4177139.html

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