Symmetric Tree
LeetCode #101
Description:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Example:
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
Idea:
bool isSymmetric(TreeNode* root)
parameter只有一个root,不好写,但把parameter变为两个root,就很好写了。
Note,不用改变function number,通过不同的parameter可以overloading。
Code:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL) return true;
return isSymmetric(root->left, root->right);
}
bool isSymmetric(TreeNode *p, TreeNode *q){
if(p==NULL && q==NULL) return true;
if(p==NULL || q==NULL) return false;
if(p->val!=q->val) return false;
return isSymmetric(p->left, q->right)&&isSymmetric(p->right, q->left);
}
};