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

LeetCode[Tree]: Symmetric Tree

时间:2014-11-27 09:18:04      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:symmetric tree   leetcode   递归   迭代   算法   

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

标签:symmetric tree   leetcode   递归   迭代   算法   

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

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