654. Maximum Binary Tree

来源:互联网 发布:淘宝定制家具付款流程 编辑:程序博客网 时间:2024/06/01 12:36

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.

----------------------------------------------------------------------------------------

2017/11/25

/**
 * 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 buildBinaryTree(nums,0,nums.length-1);
    }
    public TreeNode buildBinaryTree(int[] nums,int start,int end){
        if(start>end){
            return null;
        }
        int max = nums[start];
        int current = start;
        for(int i = start+1;i<=end;i++){                         //这里注意循环的开始为start+1;
            if(nums[i]>max){
                max = nums[i];
                current = i;
            }
        }
        TreeNode root = new TreeNode(max);
        root.left = buildBinaryTree(nums,start,current-1);
        root.right = buildBinaryTree(nums,current+1,end);
        return root;
    }
    
}

原创粉丝点击