Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
解题思路:先判断根节点是不是存在,如果存在,则可转换为比较左右子树是不是镜像的问题,可递归求解。
class Solution {
public:
bool mirrorTree(TreeNode *leftTree,TreeNode *rightTree)
{
if(NULL == leftTree && NULL == rightTree)
return true;
if(NULL == leftTree || NULL == rightTree)
return false;
if(leftTree->val == rightTree->val)
return (mirrorTree(leftTree->left,rightTree->right) && mirrorTree(leftTree->right,rightTree->left));
else return false;
}
bool isSymmetric(TreeNode* root) {
if(NULL == root)
return true;
if(NULL == root->left && NULL == root->right)
return true;
else if(NULL == root->left || NULL == root->right)
return false;
return mirrorTree(root->left,root->right);
}
};