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.
题目:给定一棵树,看是否对称
思路:我的思路是先看是不是空树和只有一个根节点,之后写个compare()函数来判断左右节点是否相同。
class Solution {
public:
bool compare(TreeNode* p,TreeNode* q)
{
if(!p&&!q)
return true;
else if((!p&&q)||(p&&!q))
return false;
else if(p->val!=q->val)
return false;
return compare(p->left,q->right)*compare(p->right,q->left);
}
bool isSymmetric(TreeNode* root) {
TreeNode *p=root;
if(p==NULL)
return true;
TreeNode* root_left=root->left;
TreeNode* root_left=root->right;
return compare(root_left,root_left);
}
};