您的位置:首页 > 其它

Leetcode:Symmetric Tree

2015-01-02 20:57 309 查看
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.

分析:

1. 递归法。如果一个树是symmetric的,那么它的左右子树是镜像对称的。对于判断两个树是否镜像对称,如果两棵树的根节点值相同,并且树A的左孩子跟树B的右孩子镜像对称且树A的右还在和树B的左还在镜像对称,那么树A和B是镜像对称的。代码如下:

class Solution {
public:
bool isSymmetric(TreeNode *root) {
if(root == NULL) return true;
return is_mirror(root->left, root->right);
}
bool is_mirror(TreeNode *l, TreeNode *r){
if(l == NULL || r == NULL) return l == r;
if(l->val != r->val) return false;
return is_mirror(l->left, r->right) && is_mirror(l->right, r->left);
}
};


迭代版算法,是利用栈的树迭代遍历算法的变体。主要思想是把对称的两个节点同时Push到栈里,然后每次从栈顶pop两个节点判断是否相同。代码如下:

class Solution {
public:
bool isSymmetric(TreeNode *root) {
if(root == NULL) return true;
stack<TreeNode *> s;
s.push(root->left);
s.push(root->right);

while(!s.empty()){
TreeNode *r = s.top();s.pop();
TreeNode *l = s.top();s.pop();
if(r == NULL && l == NULL) continue;//this is very import
if(r == NULL || l == NULL) return false;
if(r->val != l->val) return false;

s.push(r->left);
s.push(l->right);
s.push(r->right);
s.push(l->left);
}

return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: