Symmetric Tree

Posted on 2017-01-04 21:00  沙_shine  阅读(117)  评论(0编辑  收藏  举报

原题链接:https://leetcode.com/problems/symmetric-tree/

题目如下:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3
目前,我只实现了递归版本,非递归版本稍后更新。
递归版本代码如下:
语言:C++
 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 == NULL)    
14             return true;
15         else
16             return isSymmetric(root->left,root->right);
17     }
18     bool isSymmetric(TreeNode* lefttree,TreeNode* righttree)
19     {
20         if((lefttree == NULL)&&(righttree == NULL)) 
21         {
22             return true;
23         }
24         else if((lefttree == NULL)&&(righttree != NULL))   
25         {
26             return false;
27         }
28         else if((lefttree != NULL)&&(righttree == NULL))   
29         {
30             return false;
31         }
32         else if((lefttree != NULL)&&(righttree != NULL)&&(lefttree->val != righttree->val))
33         {
34             return false;
35         }
36         else
37         {
38             return isSymmetric(lefttree->left,righttree->right) && isSymmetric(lefttree->right,righttree->left);
39         }
40     }
41 };

 此代码在最开始提交时,结果总是不对。原因:

将 "lefttreel != righttree" 改为"lefttree->val != righttree->val",需要比较的不是节点,而是节点的value。

另外,今天get到一句感触颇深的话:不能靠Debug写代码,与各位共勉,谢谢!