Algorithm-Tree-Maximum Binary Tree

Insert picture description here
Insert picture description here
Insert picture description here

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    
    public TreeNode constructMaximumBinaryTree(int[] nums) {
    
    
        if(nums == null || nums.length == 0) {
    
    
            return null;
        }

        return help(nums, 0, nums.length - 1);
    }

    public TreeNode help(int[] nums, int start, int end) {
    
    
        if(start > end) {
    
    
            return null;
        }
        
        int maxIndex = start;//此处必须取 start和end之间的一个值
        for(int i = start; i <= end; i++) {
    
    
            if(nums[i] > nums[maxIndex]) {
    
    
                maxIndex = i;
            }
        }
        TreeNode root = new TreeNode(nums[maxIndex]);

        root.left = help(nums, start, maxIndex - 1);
        root.right = help(nums, maxIndex + 1, end);

        return root;
    }
}

Guess you like

Origin blog.csdn.net/qq_45100361/article/details/113477047