Description:
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:
Note:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3Bonus points if you could solve it both recursively and iteratively
Solution:
Analysis and Thinking:
给定要求在一棵二叉树作为输入的情况下,检查它是否是它自身的轴对称的镜像。这题比较简单,只需要看图做题,利用递归的方法就可以解决,一开始递归左右子树,当满足以下条件:第一棵树的右子树与第二棵树的左子树相同且第二棵树的右子树与第一棵树的左子树也完全相同时,我们就说该树满足对称条件,是轴对称的镜像
Steps:
1.判断根节点是否为空,若为空,返回true
2.如果左右节点都不为空,进入递归,递归过程中,当出现任意一次当前两节点值不相等,则返回false
3.直到递归至叶子节点,则其左右子树为空,递归返回true,为正确结果
Codes:
/**
* 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 isSymmetric(TreeNode* root) {
if(root==NULL)
return true;
if(root->left!=NULL&&root->right!=NULL)
return isMinor(root->left,root->right);
if(root->left==NULL&&root->right==NULL)
return true;
return false;
}
private:
bool isMinor(TreeNode* x,TreeNode* y){
if(x==NULL&&y==NULL)
return true;
if(x!=NULL&&y!=NULL){
if(x->val!=y->val)
return false;
else if(x->left==NULL&&x->right==NULL&&y->left==NULL&&y->right==NULL)
return true;
else{
if(isMinor(x->left,y->right)&&isMinor(x->right,y->left))
return true;
}
}
return false;
}
};
Results: