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
\ \
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
问题分析:判断一个树是否为对称二叉树。要解决可以用迭代的方法也可以用递归的办法,但是能用迭代尽量少用递归。使用迭代的算法一般需要借助栈或者队列,我采用的是堆来分别保存左右子树的数据,需要注意的地方就是在放入的过程中,左右子树的左右孩子的放入顺序刚好相反。实现代码如下:
/**
* 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) {
stack<TreeNode*> tstack1;
stack<TreeNode*> tstack2;
TreeNode *p=root;
if(p!=NULL){
tstack1.push(p->left);
tstack2.push(p->right);
while((!tstack1.empty())&&(!tstack2.empty())){
TreeNode *t1=tstack1.top();
TreeNode *t2=tstack2.top();
tstack1.pop();
tstack2.pop();
if (NULL == t1 && NULL == t2)
continue;
if (NULL == t1 || NULL == t2)
return false;
if (t1->val != t2->val)
return false;
tstack1.push(t1->left);
tstack1.push(t1->right);
tstack2.push(t2->right);
tstack2.push(t2->left);
}
return true;
}
else
return true;
}
};