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? > read more on how binary tree is serialized on OJ.
solution 1: 用dfs中序遍历tree,将遍历出来的node的value和height存在数组中,如果数组是回文的,那么就是对称的。
solution 2: 用递归,转换为子树对称问题。
solution 3: 将solution 2改成非递归的方案, 用两个stack
solution 1:
#include <stack>
/**
* 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 || (root->left == NULL && root->right == NULL))
return true;
stack<TreeNode*> elements;
stack<int> height;//store each element's level.
vector<int> values;//store the dfs elements. detect if huiwen.
vector<int> levels;//store the dfs element's level, detect if equal.
elements.push(root);
height.push(1);
bool left = true;//left subtree can be visit.
int level = 1;
//dfs
while(!elements.empty())
{
TreeNode* leftNode = elements.top();
//iterate left
while(leftNode->left && left)
{
leftNode = leftNode->left;
elements.push(leftNode);
level++;
height.push(level);
}
//visit node.
TreeNode* top = elements.top();
values.push_back(top->val);
levels.push_back(height.top());
level = height.top();
height.pop();
elements.pop();
left = false;
//push right.
if(top->right)
{
elements.push(top->right);
left = true;
level++;
height.push(level);
}
}
for(int i = 0 ; i < values.size()/2; i++)
{
if(values[i] != values[values.size() - i - 1] || levels[i] != levels[levels.size() - i -1])
return false;
}
return true;
}
};
solution 2:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root)return true;
return g(root->left,root->right);
}
bool g(TreeNode*n,TreeNode*p){
if(!n&&!p) return true;
if(!n||!p) return false;
return n->val == p->val && g(n->left,p->right) && g(n->right,p->left);
}
};
solution 3:
bool isSymmetric(TreeNode* root) {
stack<TreeNode*> s1;
stack<TreeNode*> s2;
if(root == NULL) return true;
s1.push(root); s2.push(root);
while(!s1.empty() && !s2.empty()){
TreeNode* n1 = s1.top();
TreeNode* n2 = s2.top();
s1.pop();
s2.pop();
if(n1->val != n2->val) return false;
if(n1->left != NULL && n2->right != NULL){
s1.push(n1->left);
s2.push(n2->right);
}
if(n1->right != NULL && n2->left != NULL){
s1.push(n1->right);
s2.push(n2->left);
}else if((n1->left == NULL && n2->right == NULL) || (n1->right == NULL && n2->left ==NULL))
continue;
else return false;
}
return true;
}