Concise Java


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

Log in to reply
 

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