Maximum binary tree --p654--recursive construction

Similar to p106

package tree;

import sun.reflect.generics.tree.Tree;

/**
 * Given an integer array with no repeating elements. A maximal binary tree constructed from this array is defined as follows:

 The root of a binary tree is the largest element in the array.
 The left subtree is the largest binary tree constructed from the left part of the largest value in the array.
 The right subtree is the largest binary tree constructed from the right part of the largest value in the array.

 Build the largest binary tree from the given array and output the root node of this tree.

 Example 1:

 Input: [3,2,1,6,0,5]
 Input: Return the root node of the following tree:

 6
 /   \
 3     5
 \    /
 2  0
 \
 1

 Notice:

 The size of the given array is between [1, 1000].


 */
public class p654 {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
            if(nums.length==0)return null;
            if(nums.length==1)return new TreeNode(nums[0]);
            TreeNode root=null;
            root=buildTree(nums);
            return root;
    }

    public TreeNode buildTree(int []nums){
        if(nums.length==0)return null;
        int i,max=0,maxIndex=-1;
        for(i=0;i<nums.length;i++){     //找到最大值
            if(max<nums[i]){
                max=nums[i];
                maxIndex=i;
            }
        }
        TreeNode node = new TreeNode(nums[maxIndex]);
         // Left subtree array 
        int leftTree[]= new  int [maxIndex];
        System.arraycopy(nums,0,leftTree,0,leftTree.length);
        //右子树数组
        int rightTree[]=new int[nums.length-maxIndex-1];
        System.arraycopy(nums,maxIndex+1,rightTree,0,rightTree.length);
        node.left=buildTree(leftTree);
        node.right=buildTree(rightTree);
        return node;
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325329220&siteId=291194637