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

Symmetric Tree

时间:2017-01-04 21:50:47      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:.com   lan   not   bug   今天   更新   win   whether   round   

原题链接: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写代码,与各位共勉,谢谢!

Symmetric Tree

标签:.com   lan   not   bug   今天   更新   win   whether   round   

原文地址:http://www.cnblogs.com/jingjingblog/p/6250213.html

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