首页 > 其他 > 详细

LeetCode[Tree]: Symmetric Tree

时间:2014-11-27 09:14:53      阅读:214      评论:0      收藏:0      [点我收藏+]

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

Recursive Algorithm

class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        return root ? isSymmetric(root->left, root->right) : true;
    }

private:
    bool isSymmetric(TreeNode *left, TreeNode *right) {
        if (!left && !right) return true;
        if ( left && !right) return false;
        if (!left &&  right) return false;

        if (left->val != right->val) return false;

        if (!isSymmetric(left->left,  right->right)) return false;
        if (!isSymmetric(left->right, right->left )) return false;

        return true;
    }
};


Iterative Algorithm

class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if (!root) return true;

        stack<TreeNode *> leftStack, rightStack;
        leftStack.push(root->left);
        rightStack.push(root->right);

        while (!leftStack.empty()) {
            TreeNode *left = leftStack.top(),   *right = rightStack.top();
            leftStack.pop();                    rightStack.pop();

            if (!left && !right) continue;
            if (!left &&  right) return false;
            if ( left && !right) return false;
            if (left->val != right->val) return false;

            leftStack.push(left->left );        rightStack.push(right->right);
            leftStack.push(left->right);        rightStack.push(right->left);
        }


        return true;
    }
};


LeetCode[Tree]: Symmetric Tree

原文:http://blog.csdn.net/chfe007/article/details/41531561

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!