leetcode-654- largest binary tree

Title:
Given integer no repeating array elements. In this array defines a maximum binary tree constructed as follows:
binary tree is the root of the maximum element in the array.
Left subtree is constructed by the maximum value of the left part of the array the maximum binary tree.
Right subtree is constructed by the maximum value of the right part of the array the maximum binary tree.
Construction of the binary tree by the maximum given array, and outputs the root of this tree.

Example 1:
Input: [3,2,1,6,0,5]
Input: Returns the root of this tree below:
image.png
Note: The
size of a given array between [1, 1000].

Resolution:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
        time complexity : O(n)
        
        1.新建一个stk vector类型栈
        2.生成node
        3.stk为空或当前节点node小于stk顶层节点,则stk顶层节点的右子树设为当前node,并将node插入stk中
        4.若不满足,依次pop stk中元素 ,直到满足条件,并将当前节点的右子树设为最后一个pop的节点
        注意:stk是严格按照将降序排列的
 * };
 */
class Solution {
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        vector<TreeNode *> stk;//按降序排列   栈底元素最大
        for(const auto num : nums){
            TreeNode*  node = new TreeNode(num);
            while(!stk.empty() && stk.back()->val < num){  //stk中最大值小于当前节点
                node->left = stk.back();    
                stk.pop_back();
            }
            if(!stk.empty()){
                stk.back()->right = node;
            }
            stk.push_back(node);
        }
        return stk[0];   //stk是按照降序排列的,栈顶元素就最大值
    }
};

Guess you like

Origin www.cnblogs.com/fightingcode/p/11029072.html