LintCode "Max Tree"

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;
     }
 };
原文地址:https://www.cnblogs.com/tonix/p/4852999.html