Easy to understand Java Solution, similar to "Convert Sorted Array to Binary Search Tree"


  • 0
    E
    /**
     * 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 createMax(nums,0,nums.length-1);
        }
        public TreeNode createMax(int nums[], int start, int end){
            if(start>end){
                return null;
            }
            int max= Integer.MIN_VALUE,pos=-1,i=start;
            while(i<=end){
                if(max<nums[i]){
                    max=nums[i];
                    pos=i;
                }
                i++;
            }
            TreeNode root=new TreeNode(max);
            root.left=createMax(nums,start,pos-1);
            root.right=createMax(nums,pos+1,end);
            return root;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.