码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode:Symmetric Tree

时间:2015-01-02 22:15:05      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:

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是镜像对称的。代码如下:

 1 class Solution {
 2 public:
 3     bool isSymmetric(TreeNode *root) {
 4         if(root == NULL) return true;
 5         return is_mirror(root->left, root->right);
 6     }
 7     bool is_mirror(TreeNode *l, TreeNode *r){
 8         if(l == NULL || r == NULL) return l == r;
 9         if(l->val != r->val) return false;
10         return is_mirror(l->left, r->right) && is_mirror(l->right, r->left);
11     }
12 };

迭代版算法,是利用栈的树迭代遍历算法的变体。主要思想是把对称的两个节点同时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;
    }
};

 

Leetcode:Symmetric Tree

标签:

原文地址:http://www.cnblogs.com/Kai-Xing/p/4198800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!