Maximum Binary Tree

654. Maximum Binary Tree

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

 

Construct the maximum tree by the given array and output the root node of this tree.

Example 1:

Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1

Note:

  1. The size of the given array will be in the range [1,1000].

 

DFS,找到陣列中最大值和最大值的位置,用最大值建立 node,再根據最大值位置將陣列分成左半和右半繼續做遞迴,其中若最大值為最左邊則左子樹直接設為 null,若最大值在右邊則右子樹則直接設為 null

public TreeNode constructMaximumBinaryTree(int[] nums) {
    if(nums.length == 1) {
        return new TreeNode(nums[0]);
    }

    int index = 0, max = nums[0];
    for(int i=0; i<nums.length; i++) {
        if(max < nums[i]) {
            max = nums[i];
            index = i;
        }            
    }

    TreeNode node = new TreeNode(max);
    node.left = index == 0 ? null : constructMaximumBinaryTree(Arrays.copyOfRange(nums, 0, index));
    node.right = index == nums.length - 1 ? null : constructMaximumBinaryTree(Arrays.copyOfRange(nums, index + 1, nums.length));

    return node;
}