1. 程式人生 > >[LeetCode]654. Maximum Binary Tree最大堆二叉樹

[LeetCode]654. Maximum Binary Tree最大堆二叉樹

== lee 最大 con clas post uil return eno

每次找到數組中的最大值,然後遞歸的構建左右樹

public TreeNode constructMaximumBinaryTree(int[] nums) {
        if (nums.length==0) return null;
        return builder(nums,0,nums.length-1);
    }
    public TreeNode builder(int[] nums,int sta,int end)
    {
        /*
        思路就是每次找到最大值,然後分為兩個子數組遞歸構建左右樹
         */
        if
(sta>end) return null; int max = Integer.MIN_VALUE; int index = -1; for (int i = sta; i <= end ; i++) { if (nums[i]>max) { max = nums[i]; index = i; } } TreeNode root = new TreeNode(max); root.left
= builder(nums,sta,index-1); root.right = builder(nums,index+1,end); return root; }

[LeetCode]654. Maximum Binary Tree最大堆二叉樹