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

leetcode_num101_Symmetric Tree

时间:2015-04-04 23:50:46      阅读:338      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode      

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

标签:c++   leetcode      

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

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