LeetCode.654. Maximum Binary Tree

https://leetcode.com/problems/maximum-binary-tree/

递归就完事了

class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return f(nums, 0, nums.length - 1);
    }
    
    public TreeNode f(int[] nums, int start, int end) {
        
        if (start > end) {
            return null;
        }
        
        int max = 0;
        int maxI = 0;
        for (int i = start; i <= end; i++) {
            if (i == start) {
                max = nums[i];
                maxI = i;
            } else {
                if (nums[i] > max) {
                    max = nums[i];
                    maxI = i;
                }
            }
        }
        
        TreeNode t = new TreeNode(max);
        t.left = f(nums, start, maxI - 1);
        t.right = f(nums, maxI + 1, end);
        
        return t;
    }
}
点赞