leetcode654题--最大二叉树
- leetcode654 - 最大二叉树
- 解题思路
- 代码演示
- 二叉树专题
leetcode654 - 最大二叉树
leetcode654 - 最大二叉树 原题链接
给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
创建一个根节点,其值为 nums 中的最大值。
递归地在最大值 左边 的 子数组前缀上 构建左子树。
递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树 。
示例:
输入:nums = [3,2,1,6,0,5]
输出:[6,3,5,null,2,0,null,null,1]
解释:递归调用如下所示:
- [3,2,1,6,0,5] 中的最大值是 6 ,左边部分是 [3,2,1] ,右边部分是 [0,5] 。
- [3,2,1] 中的最大值是 3 ,左边部分是 [] ,右边部分是 [2,1] 。
- 空数组,无子节点。
- [2,1] 中的最大值是 2 ,左边部分是 [] ,右边部分是 [1] 。
- 空数组,无子节点。
- 只有一个元素,所以子节点是一个值为 1 的节点。
- [0,5] 中的最大值是 5 ,左边部分是 [0] ,右边部分是 [] 。
- 只有一个元素,所以子节点是一个值为 0 的节点。
- 空数组,无子节点。
示例2:
输入:nums = [3,2,1]
输出:[3,null,2,null,1]
提示:
1 <= nums.length <= 1000
0 <= nums[i] <= 1000
nums 中的所有整数 互不相同
解题思路
数组中以最大值来分,左边就是左树,右边就是右树,
我们先找到最大值的下标,将数组分成两部分
然后左边用来生成左树,右边用来生成右树
然后去递归。
代码演示
/**
 * 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 process(nums,0,nums.length - 1);
    }
	/**
	* 递归方法 
	*/
    public static TreeNode process(int[]nums,int L,int R){
        //base case 越界就返回
        if(L > R){
            return null;
        }
        int headIndex = getMax(nums,L,R);
        //生成头节点
        TreeNode head = new TreeNode(nums[headIndex]);
        head.left = process(nums,L,headIndex - 1);
        head.right = process(nums,headIndex + 1,R);
        return head;
    }
	/**
	* 拿到数组中最大值的下标
	* L 是边界
	* R 是右边界
	*/
    public static int getMax(int[]arr,int L,int R){
        int k = -1;
        int max = Integer.MIN_VALUE;
        for(int i = L;i <= R;i++){
            if(arr[i] > max){
                k = i;
                max = arr[i];
            }
        }
        return k;
    }
}
二叉树专题
从前序与中序遍历序列构造二叉树
镜像二叉树和求二叉树最大深度
二叉树的直径
二叉树:填充每个节点的下一个右侧节点指针
二叉树专题-前序中序和后序遍历的递归实现和非递归实现
二叉树的序列化和反序列化




















