This is a working solution of the problem:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return helper(nums, 0, nums.length-1);
}
public TreeNode helper(int[] nums, int low, int high){
if (high < low){ return null; }
//find max element's index
int maxIndex = getMaxIndex(nums, low, high);
//construct root node
TreeNode root = new TreeNode(nums[maxIndex]);
//generate left subtree from the left part of subarray
root.left = helper(nums, low, maxIndex-1);
//generate right sub tree from the right part of subarray
root.right = helper(nums, maxIndex+1, high);
return root;
}
public int getMaxIndex(int[] nums, int low, int high){
int maxIndex = low;
for (int i = low+1; i <= high; i++){
if (nums[i] > nums[maxIndex]){
maxIndex = i;
}
}
return maxIndex;
}
}
Can someone please walk me through the problem and all of the recursive calls? Right now I do not understand how the solution builds the tree node. I'm currently walking through the problem like this.
constructMaximumBinaryTree(int[] nums)
int maxIndex = getMaxIndex(nums, 0, 5) so maxIndex = 3.
TreeNode root = 6.
root.left = helper(nums, 0, 2) so maxIndex = 0.
TreeNode root = 3.
root.left = helper(nums, 0, -1), which triggers the base case and returns null.
I get lost after step 6. After step 6 returns null, do I move on to root.right = helper(nums, maxIndex+1, high)? If so, what would maxIndex and high be? And what are the next steps?