Title

#树#递归#最大二叉树

 

 

/**
 * 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 buildNode(nums,0,nums.length);
    }
    public TreeNode buildNode(int[]nums,int l,int r) {
        if(l == r) {
            return null;
        }
        int t = maxIndex(nums,l,r);
        TreeNode root = new TreeNode(nums[t]);
        root.left = buildNode(nums,l,t);
        root.right = buildNode(nums,t+1,r);
        return root;
    }
    public int maxIndex(int[]nums,int l,int r) {
        int index = l;
        for(int i = l;i<r;++i) {
            if(nums[index]<nums[i]) {
                index = i;
            }
        } 
        return index;
    }
}

 

posted @ 2020-07-15 17:44  .geek  阅读(96)  评论(0编辑  收藏  举报