Max Tree
Question
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.
Example Given[2, 5, 6, 0, 3, 1]
, the max tree constructed by this array is:
ChallengeO(n)
time and memory.
Thoughts
采用up-down的方法就是recursive call
采用Bottom-up
loop through the array, 建立一个stack, 对于每一个elment nums[i]
if nums[i] > stack[-1], 要找到stack里比nums[i]小的最近的最大值, 所以一直pop并且nums[i].left = stack.pop()
直到nums[i] < stack[-1], 这时stack的顶top是比nums[i]大的左边的第一个值,nums[i]先设为它的right child(如果之后有值在top和nums[i]之间,会因为第一步被更新,它会一直指向最新nums[i]如果需要的话)
将nums[i] push到stack上
最终return stack的第一个
大沉底小出去。for loop所有数,栈内所有比它小的数弹出,大数留着。压入栈时候就是算好了左值的,因为根据已有信息已经能算左值了,新来数时栈内大数都会试探性赋右值。
Solution
recursive版本
Last updated