首页 > 其他 > 详细

【LeetCode】101 - Symmetric Tree

时间:2015-08-11 07:00:09      阅读:200      评论: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

 

Note:Bonus points if you could solve it both recursively and iteratively.

OJ‘s Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where ‘#‘ signifies a path terminator where no node exists below.

Here‘s an example:

   1
  /  2   3
    /
   4
         5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

Solution 1: 递归,left对应right,left->left对应right->right,left->right对应right->left

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isSymmetric(TreeNode* root) {
13         if(!root)return true;
14         return isSymTree(root->left,root->right);
15     }
16     bool isSymTree(TreeNode *p,TreeNode *q){
17         if(!isSameNode(p,q))
18             return false;
19         else if(!p&&!q)
20             return true;
21         else
22             return isSymTree(p->left,q->right) && isSymTree(p->right,q->left);
23     }
24     bool isSameNode(TreeNode *p,TreeNode *q){
25         if(!p&&!q)      //必需加上这个判断条件,否则若p、q为空下面的->val会运行时错误
26             return true;
27         else if((!p&&q)||(p&&!q)||(p->val!=q->val))     //利用||的短路效应避免运行时错误
28             return false;
29         return true;
30     }
31 };

Solution 2 :非递归,待续

【LeetCode】101 - Symmetric Tree

原文:http://www.cnblogs.com/irun/p/4719686.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!