首页 > 其他 > 详细

leetCode Symmetric Tree

时间:2014-10-06 10:49:10      阅读:135      评论:0      收藏:0      [点我收藏+]

非递归解法

/**
 * 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) {
       stack <TreeNode*> stackLeft;
       stack <TreeNode*> stackRight;
       
       if(root == NULL ||(root && (!root->left) && (!root->right))){
           return true;
       }
       
       if((root->left && (!root->right))||(!root->left && root->right)){
           return false;
       }
       TreeNode *pLeft = root->left;
       TreeNode *pRight = root->right;
       while((pLeft||(!stackLeft.empty())) && (pRight ||(!stackRight.empty()))){
            while(pLeft && pRight){
               
                if(pLeft->val != pRight->val){
                    return false;
                }
                stackLeft.push(pLeft); 
                pLeft = pLeft->left;
                stackRight.push(pRight);
                pRight = pRight->right;
            }
            
            if(pLeft || pRight){
                return false;
            }
            
            pLeft = stackLeft.top();
            stackLeft.pop();
            pLeft = pLeft->right;
            
            pRight = stackRight.top();
            stackRight.pop();
            pRight = pRight->left;
       }
       
       if( (pLeft||(!stackLeft.empty())) || (pRight ||(!stackRight.empty()))){
           return false;
       }
       
       return true;
    }
};</span>


递归解法

leetCode Symmetric Tree

原文:http://blog.csdn.net/wyj7260/article/details/39826301

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