Java recursive solution


  • 0
    U
    public class Solution {
        public TreeNode constructMaximumBinaryTree(int[] nums) {
            if (nums.length == 0) {
                return null;
            }
            return helper(nums, 0, nums.length - 1);
        }
        
        private static TreeNode helper(int[] nums, int left, int right) {
            if (left > right) {
                return null;
            }
            if (left == right) {
                return new TreeNode(nums[left]);
            }
            int max = Integer.MIN_VALUE, index = left;
            for (int i = left; i <= right; i++) {
                if (max < nums[i]) {
                    max = nums[i];
                    index = i;
                }
            }
            TreeNode root = new TreeNode(max);
            root.left = helper(nums, left, index - 1);
            root.right = helper(nums, index + 1, right);
            return root;
        }
    }
    

Log in to reply
 

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