[LeetCode]最大二叉树

刚健朴实的递归,不过要注意递归跳出的条件和递归进入的条件,不然很容易死循环然后爆栈或者越界。

问题链接:https://leetcode-cn.com/problems/maximum-binary-tree/

代码:

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return BinaryTree(nums,0,nums.length-1);
    }
    public TreeNode BinaryTree(int[] nums,int begin,int end) {
        int index = searchMax(nums,begin,end);
        if(index==-1){
            return null;
        }
        TreeNode t =new TreeNode(nums[index]);
        t.left = BinaryTree(nums,begin,index-1);
        t.right = BinaryTree(nums,index+1,end);
        return t;
    }

    int searchMax(int[] num,int start,int end){
        int MAX=Integer.MIN_VALUE;
        int index = -1;
        for(int i=start;i<=end;i++){
            if(num[i]>MAX){
                MAX=num[i];
                index = i;
            }
        }
        return index;
    }

猜你喜欢

转载自blog.csdn.net/sinat_37273780/article/details/84959361