题目:
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:
But the following [1,2,2,null,3,null,3]
is not:
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);
}
};