zoukankan      html  css  js  c++  java
  • leetcode654 Maximum Binary Tree

    思路:

    使用单调栈可以达到O(n)。

    实现:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution
    11 {
    12 public:
    13     TreeNode* constructMaximumBinaryTree(vector<int>& nums)
    14     {
    15         stack<TreeNode*> st;
    16         for (auto it: nums)
    17         {
    18             TreeNode* tmp = new TreeNode(it), *last = NULL;
    19             while (!st.empty() && tmp->val > st.top()->val)
    20             {
    21                 last = st.top(); st.pop();
    22             }
    23             tmp->left = last;
    24             if (!st.empty()) st.top()->right = tmp;
    25             st.push(tmp);
    26         }
    27         TreeNode* res = NULL;
    28         while (!st.empty())
    29         {
    30             res = st.top(); st.pop();
    31         }
    32         return res;
    33     }
    34 }
  • 相关阅读:
    Memcached初识
    排序
    查找
    Redis初识

    C#
    C#
    C#
    C#
    C#
  • 原文地址:https://www.cnblogs.com/wangyiming/p/11348479.html
Copyright © 2011-2022 走看看