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

LintCode "Max Tree"

时间:2015-10-03 07:19:15      阅读:314      评论:0      收藏:0      [点我收藏+]

标签:

Something new I learnt from it: what is Treap and a O(n) construction https://en.wikipedia.org/wiki/Cartesian_tree#Efficient_construction

class Solution
 {
 public:
     /**
      @param A: Given an integer array with no duplicates.
      @return: The root of max tree.
      */
     TreeNode* maxTree(vector<int> A) {
         size_t n = A.size();
         if (!n)
             return nullptr;

         TreeNode *pRoot = nullptr;
         stack<TreeNode*> stk;

         for(auto v : A)
         {
             TreeNode *pNew = new TreeNode(v);
             if(!stk.empty())
             {
                 TreeNode *pLast = stk.top();
                 if(pNew->val < pLast->val)
                 {
                     pLast->right = pNew;
                 }
                 else // pNew->val > pLast->val
                 {
                     while(!stk.empty())
                     {
                         if(stk.top()->val < pNew->val)
                         {
                             stk.pop();
                         }else break;
                     }
                     if(!stk.empty())
                     {
                         TreeNode *pParent = stk.top();
                         TreeNode *pTmp = pParent->right;
                         pParent->right = pNew;
                         pNew->left = pTmp;
                     }
                     else
                     {
                         pNew->left = pRoot;
                     }
                 }
             }
             stk.push(pNew); // new node is always right most

             if(!pRoot || v > pRoot->val)
             {
                 pRoot = pNew;
             }
         }

         return pRoot;
     }
 };

LintCode "Max Tree"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4852999.html

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