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.

/**
 * 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 constructMaximumBinaryTree(nums, 0, nums.length - 1);
    }

    public TreeNode constructMaximumBinaryTree(int[] nums, int start, int end) {
        if(start > end)
            return null;
        int max = start;
        for(int i = start; i <= end; i++) {
            if(nums[i] > nums[max])
                max = i;
        }

        TreeNode root = new TreeNode(nums[max]);
        TreeNode left = constructMaximumBinaryTree(nums, start, max - 1);
        TreeNode right = constructMaximumBinaryTree(nums, max + 1, end);
        root.left = left;
        root.right = right;

        return root;
    }
}

results matching ""

    No results matching ""