描述
Given an integer array with no duplicates. A max tree building on this array is defined as follow:
- The root is the maximum number in the array
- The left subtree and right subtree are the max trees of the subarray divided by the root number.
Construct the max tree by the given array in O(n)
time/space complexity.
Example 1:
1 | Input:[2, 5, 6, 0, 3, 1] |
Example 2:
1 | Input:[6,4,20] |
思路
维护一个单调递减单调栈. 如果当前值比stack[-1]
要大, 循环弹出栈顶. 当前值是第一个比在弹出值右侧并且比它大的. 所以更新当前节点的左子节点.
弹出完毕, 如果此时栈非空, 说明栈顶是在当前值左侧第一个比它大的. 栈顶的右子节点应该是当前节点.
代码
1 | """ |