Maximum Binary Tree

https://www.lintcode.com/problem/maximum-binary-tree/description

/**
 * Definition of TreeNode:
 * public class TreeNode {
 * public int val;
 * public TreeNode left, right;
 * public TreeNode(int val) {
 * this.val = val;
 * this.left = this.right = null;
 * }
 * }
 */

public class Solution {
    /**
     * @param nums: an array
     * @return: the maximum tree
     */
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        // Write your code here
        return build(nums, 0, nums.length - 1);
    }

    private TreeNode build(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }
        int index = left;
        for (int i = left + 1; i <= right; i++) {
            if (nums[i] > nums[index]) {
                index = i;
            }
        }
        TreeNode node = new TreeNode(nums[index]);
        node.left = build(nums, left, index - 1);
        node.right = build(nums, index + 1, right);
        return node;
    }
}

你可能感兴趣的:(Maximum Binary Tree)