首页 > 其他 > 详细

leetcode_num101_Symmetric Tree

时间:2015-04-04 23:49:00      阅读:387      评论: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

递归 依次比较左左、右右,左右、右左

/**
 * Definition for binary tree
 * 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)
            return true;
        bool res=Compare(root->left,root->right);
        return res;
    }
    bool Compare(TreeNode*Left,TreeNode*Right){
        bool res=false;
        if(!Left&&!Right)
            return true;
        else if(Left&&Right&&Left->val==Right->val){
            bool check1=Compare(Left->left,Right->right);
            bool check2=Compare(Left->right,Right->left);
            res=check1&&check2;
        }
        return res;
    }
};



循环 使用两个栈分别按递归的顺序依次存储左子树和右子树的节点

尽量多写几种情况吧 不明白为何会报runtime error

class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if(!root||(!root->left&&!root->right))
            return true;
        stack<TreeNode*> stack1;
        stack<TreeNode*> stack2;
        stack1.push(root->left);
        stack2.push(root->right);

        while((!stack1.empty())&&(!stack2.empty())){
            TreeNode* L=stack1.top();
            TreeNode* R=stack2.top();
            stack1.pop();
            stack2.pop();
            if((!L)&&(!R))
                continue;
            if(!L||!R)
                return false;
            if(L->val!=R->val)
                return false;
            stack1.push(L->left);
            stack2.push(R->right);
            stack1.push(L->right);
            stack2.push(R->left);
        }
        return true;
        
    }
};


leetcode_num101_Symmetric Tree

原文:http://blog.csdn.net/eliza1130/article/details/44876873

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