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

leetcode 101

时间:2016-09-12 12:31:14      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

101. 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

 

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

判断二叉树是否为平衡二叉树。

递归实现。

 

代码如下:

 

 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         {
15             return true;
16         }
17         return isSame(root->left, root->right);
18     }
19     bool isSame(TreeNode* left, TreeNode* right)
20     {
21         if(left == NULL && right == NULL)
22         {
23             return true;
24         }
25         else if(left == NULL)
26         {
27             return false;
28         }
29         else if(right == NULL)
30         {
31             return false;
32         }
33         
34         if(left->val == right->val && left->left == NULL && left->right && right->right == NULL && right->left == NULL)
35         {
36             return true;
37         }
38         else if(left->val == right->val)
39         {
40             return isSame(left->left, right->right) && isSame(left->right, right->left);
41         }
42         else
43         {
44             return false;
45         }
46         
47     }
48 };

 

leetcode 101

标签:

原文地址:http://www.cnblogs.com/shellfishsplace/p/5864219.html

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