题目
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
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means?
判断二叉树是否镜像相同。
做两个dfs,一个先左子树,后右子树;另一个先右子树,后左子树。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
vector<TreeNode*> st1,st2; //中右左dfs、中左右dfs栈
public:
bool isSymmetric(TreeNode *root) {
TreeNode *tp1,*tp2;
st1.clear();
st2.clear();
st1.push_back(root);
st2.push_back(root);
while(!st1.empty()) //dfs
{
tp1=st1.back();
st1.pop_back();
tp2=st2.back();
st2.pop_back();
if(tp1==NULL&&tp2==NULL) //比较
continue;
if(tp1!=NULL&&tp2!=NULL&&tp1->val==tp2->val)
{
st1.push_back(tp1->left);
st1.push_back(tp1->right);
st2.push_back(tp2->right);
st2.push_back(tp2->left);
}
else //不同时返回
return false;
}
return true; //通过探测
}
};