zoukankan      html  css  js  c++  java
  • 654. Maximum Binary Tree

    问题描述:

    Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

    1. The root is the maximum number in the array.
    2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
    3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

    Construct the maximum tree by the given array and output the root node of this tree.

    Example 1:

    Input: [3,2,1,6,0,5]
    Output: return the tree root node representing the following tree:
    
          6
        /   
       3     5
            / 
         2  0   
           
            1
    

    Note:

    1. The size of the given array will be in the range [1,1000].

    解题思路:

     最初这道题我是想用递归来解,先找到给定范围的数组的最大值,然后找到两边的下标范围,然后递归迭代。

    这样的时间复杂度为O(n2)

    今天学习到了一种O(n)的解法,用的是单调栈

    栈内的值是单调递减的。

    对数组的每个值n,新创建一个节点nodeN,判断n与栈顶的节点topN的值的关系,若它比栈顶的值要大,则不断弹出并将弹出节点放在当前节点nodeN的左子树直至栈顶的节点的值比它大或栈为空。这样我们可以找到最接近并且小于当前节点nodeN的值。

    若此时栈不为空,说明此时栈顶节点的值比当前节点的值要大,将当前节点放在栈顶节点的右子树。

    最后将当前节点压入栈中。

    代码:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
            stack<TreeNode*> stk;
            for(int n: nums){
                TreeNode *cur = new TreeNode(n);
                while(!stk.empty() && stk.top()->val < n){
                    cur->left = stk.top();
                    stk.pop();
                }
                if(!stk.empty()){
                    stk.top()->right = cur;
                }
                stk.push(cur);
            }
            while(stk.size()!= 1 && !stk.empty())
                stk.pop();
            return stk.top();
        }
    };
  • 相关阅读:
    使用mustache js模板引擎
    Application Cache API (二)
    scrollMonitor 滚动事件
    NPM中的那些库
    lodash 函数功能 boilerjs
    SeaJS 里版本号和时间戳管理的最佳实践
    开源前端框架纵横谈
    URI.js – 全能的URL操作库
    执行用户定义例程或聚合 "" 期间出现 .NET Framework 错误:
    一般ALV错误有两种情况
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9121463.html
Copyright © 2011-2022 走看看