1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| package com.code.note.test;
import com.code.note.tree.TreeNode; import com.code.note.util.BTreePrinter;
public class Solution {
public TreeNode constructMaximumBinaryTree(Integer[] nums) { return helper(nums, 0, nums.length-1); }
public TreeNode helper(Integer[] nums, int start, int end) { if (start > end) return null; int index = findMaxIndex(nums, start, end); TreeNode t = new TreeNode(nums[index]); t.left = helper(nums, start, index - 1); t.right = helper(nums, index + 1, end); return t; }
public int findMaxIndex(Integer[] arr, int start, int end) { int bigIndex = start; for (int i = start; i <= end; i++) { if (arr[i] > arr[bigIndex]) { bigIndex = i; } } return bigIndex; }
public static void main(String[] args) {
Solution s = new Solution(); Integer[] arr1 = {3, 2, 1, 6, 0, 5};
TreeNode root = s.constructMaximumBinaryTree(arr1); BTreePrinter.printNode(root);
} }
|