101. Symmetric Tree
2017-07-19 09:45
369 查看
题目:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree
But the following
Note:
Bonus points if you could solve it both recursively and iteratively.
思路:
这道题目,其实很简单,只要稍稍修改我前一篇博客的函数,并调用就好了Same Tree
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL&&q==NULL)
return true;
else if(p==NULL&&q!=NULL)
return false;
else if(p!=NULL&&q==NULL)
return false;
else
{
if(p->val!=q->val)
return false;
else
return isSameTree(p->left,q->right)&&isSameTree(p->right,q->left);
}
}
bool isSymmetric(TreeNode* root) {
TreeNode* temp = root;
return isSameTree(root,temp);
}
};
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.
思路:
这道题目,其实很简单,只要稍稍修改我前一篇博客的函数,并调用就好了Same Tree
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL&&q==NULL)
return true;
else if(p==NULL&&q!=NULL)
return false;
else if(p!=NULL&&q==NULL)
return false;
else
{
if(p->val!=q->val)
return false;
else
return isSameTree(p->left,q->right)&&isSameTree(p->right,q->left);
}
}
bool isSymmetric(TreeNode* root) {
TreeNode* temp = root;
return isSameTree(root,temp);
}
};
相关文章推荐
- [leedcode 101] Symmetric Tree
- 【101-Symmetric Tree(对称树)】
- [leetcode 101]Symmetric Tree
- Leetcode #101 Symmetric Tree
- leetcode 101: Symmetric Tree
- 101. Symmetric Tree
- LeetCode题解-101-Symmetric Tree
- Leetcode-101. Symmetric Tree
- leetcode 101: Symmetric Tree
- 101. Symmetric Tree
- 101. Symmetric Tree
- [leetcode 101] Symmetric Tree
- leetcode-101 Symmetric Tree
- leetcode 101: Symmetric Tree
- LeetCode 101:Symmetric Tree
- 101. Symmetric Tree
- 101. Symmetric Tree
- leetcode_c++:树: Symmetric Tree(101)
- Easy 101题 Symmetric Tree
- Easy 21 Symmetric Tree(101)