• 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();
        }
    };
  • 相关阅读:
    javascript之数组操作
    python中的类中属性元素加self.和不加self.的区别
    Q查询
    jQuery EasyUI的各历史版本和应用
    了解Entity Framework中事务处理
    C#中Abstract和Virtual的区别
    控制器post参数接收
    存储过程调用存储过程
    表变量、临时表(with as ,create table)
    LINQ TO SQL 实现无限递归查询
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9121463.html
Copyright © 2020-2023  润新知