您的位置:首页 > 编程语言 > C语言/C++

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 
[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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode