二叉树的镜像:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL)
return root;
TreeNode* temp = root->left;
if(root->right)
root->left = invertTree(root->right);
else
root->left = NULL;
if(temp)
root->right = invertTree(temp);
else
root->right = NULL;
return root;
}
};
100.Same Tree(二叉树是否相同)
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL&&q!=NULL)
return false;
if(p!=NULL&&q==NULL)
return false;
if(p==NULL&&q==NULL)
return true;
if(p->val!=q->val)
return false;
else
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
};
101.Symmetric Tree(二叉树是否对称)
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL)
return true;
else
return isSimilar(root->left,root->right);
}
bool isSimilar(TreeNode* p,TreeNode* q)
{
if(p==NULL&&q!=NULL)
return false;
if(p!=NULL&&q==NULL)
return false;
if(p==NULL&&q==NULL)
return true;
if(p->val!=q->val)
return false;
else
return isSimilar(p->left,q->right)&&isSimilar(p->right,q->left);
}
};