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.
判断一个树是否是镜像的~
自己独立思考和写出来的,开心O(∩_∩)O~~
思路就是向左右各放一个指针,分两轮判断:
- pointer1向左走,pointer向右走
- pointer1向右走,pointer向左走
再判断它们是否是相等的~
以下是递归的做法
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return isSymmetric(root->left,root->right);
}
bool isSymmetric(TreeNode* left,TreeNode* right){
if(!left && !right) return true;
if(!left || !right) return false;
if(left->val !=right->val) return false;
bool b1 = isSymmetric(left->left,right->right);
bool b2 = isSymmetric(left->right,right->left);
return b1 && b2;
}
};
思考一下非递归的做法
想复杂了,一开始以为需要一个从左往右输出,另一个从右往左输出,于是可能需要2个栈和队列。
事实上,我们推入队列或者栈的顺序除了根节点的子树之外,并不是按照一行行排列的,所以这个想法是有问题的。
于是,其实只需要用一个栈,每次弹出两个元素,保证这两个元素分别属于左边和右边的树即可
//非递归版的
bool isSymmetric(TreeNode* left,TreeNode* right){
stack<TreeNode*> Q1;
Q1.push(left);
Q1.push(right);
while(!Q1.empty()){
TreeNode* node1=Q1.top();Q1.pop();
TreeNode* node2=Q1.top();Q1.pop();
if(!node1 && !node2) continue;
if(!node1 || !node2) return false;
if(node1->val!=node2->val) return false;
Q1.push(node1->left);
Q1.push(node2->right);
Q1.push(node1->right);
Q1.push(node2->left);
}
return true;
}