You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:
Create a root node whose value is the maximum value in nums.
Recursively build the left subtree on the subarray prefix to the left of the maximum value.
Recursively build the right subtree on the subarray suffix to the right of the maximum value.
Return the maximum binary tree built from nums.
Example 1:
Input: nums = [3,2,1,6,0,5]
Output: [6,3,5,null,2,0,null,null,1]
Explanation: The recursive calls are as follow:
- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].
- The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].
- Empty array, so no child.
- The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].
- Empty array, so no child.
- Only one element, so child is a node with value 1.
- The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].
- Only one element, so child is a node with value 0.
- Empty array, so no child.
Example 2:
Input: nums = [3,2,1]
Output: [3,null,2,null,1]
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 1000
All integers in nums are unique.
Solutions
Solution 1
Thinking
The root is the interval maximum; children follow the same rule. A linear scan for the max is \(O(n^2)\) worst-case, acceptable for \(n\le 10^3\).
Take max and its index, then recurse on the two sides.
1 2 3 4 5 6 7 8 910111213141516171819
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defconstructMaximumBinaryTree(self,nums:List[int])->Optional[TreeNode]:defdfs(nums):ifnotnums:returnNoneval=max(nums)i=nums.index(val)root=TreeNode(val)root.left=dfs(nums[:i])root.right=dfs(nums[i+1:])returnrootreturndfs(nums)
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcconstructMaximumBinaryTree(nums[]int)*TreeNode{vardfsfunc(l,rint)*TreeNodedfs=func(l,rint)*TreeNode{ifl>r{returnnil}i:=lforj:=l;j<=r;j++{ifnums[i]<nums[j]{i=j}}root:=&TreeNode{Val:nums[i]}root.Left=dfs(l,i-1)root.Right=dfs(i+1,r)returnroot}returndfs(0,len(nums)-1)}
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcconstructMaximumBinaryTree(nums[]int)*TreeNode{d:=make([]int,1010)fori,v:=rangenums{d[v]=i+1}tree:=newSegmentTree(nums)vardfsfunc(l,rint)*TreeNodedfs=func(l,rint)*TreeNode{ifl>r{returnnil}val:=tree.query(1,l,r)root:=&TreeNode{Val:val}root.Left=dfs(l,d[val]-1)root.Right=dfs(d[val]+1,r)returnroot}returndfs(1,len(nums))}typenodestruct{lintrintvint}typesegmentTreestruct{nums[]inttr[]*node}funcnewSegmentTree(nums[]int)*segmentTree{n:=len(nums)tr:=make([]*node,n<<2)fori:=rangetr{tr[i]=&node{}}t:=&segmentTree{nums,tr}t.build(1,1,n)returnt}func(t*segmentTree)build(u,l,rint){t.tr[u].l,t.tr[u].r=l,rifl==r{t.tr[u].v=t.nums[l-1]return}mid:=(l+r)>>1t.build(u<<1,l,mid)t.build(u<<1|1,mid+1,r)t.pushup(u)}func(t*segmentTree)query(u,l,rint)int{ift.tr[u].l>=l&&t.tr[u].r<=r{returnt.tr[u].v}mid:=(t.tr[u].l+t.tr[u].r)>>1v:=0ifl<=mid{v=t.query(u<<1,l,r)}ifr>mid{v=max(v,t.query(u<<1|1,l,r))}returnv}func(t*segmentTree)pushup(uint){t.tr[u].v=max(t.tr[u<<1].v,t.tr[u<<1|1].v)}
Solution 3
Thinking
The segment tree is extra structure. A decreasing stack finds the nearest greater neighbor on the left: the last popped node becomes the left child, and the new top takes the current node as its right child. One pass builds the tree.
1 2 3 4 5 6 7 8 910111213141516171819
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defconstructMaximumBinaryTree(self,nums:List[int])->Optional[TreeNode]:stk=[]forvinnums:node=TreeNode(v)last=Nonewhilestkandstk[-1].val<v:last=stk.pop()node.left=lastifstk:stk[-1].right=nodestk.append(node)returnstk[0]
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcconstructMaximumBinaryTree(nums[]int)*TreeNode{stk:=[]*TreeNode{}for_,v:=rangenums{node:=&TreeNode{Val:v}varlast*TreeNodeforlen(stk)>0&&stk[len(stk)-1].Val<v{last=stk[len(stk)-1]stk=stk[:len(stk)-1]}node.Left=lastiflen(stk)>0{stk[len(stk)-1].Right=node}stk=append(stk,node)}returnstk[0]}