LeetCode:最小高度树

354 阅读1分钟

一、题目描述

二、思路分析

2.1 分析

首先高度最小的树是平衡二叉搜索树,即当树中的任意结点的左右子树高度差都不超过 1 且根节点比左节点大,比右节点小。因此我们只要根据题目给的数组构建一颗平衡二叉搜索树即可。假如数组元素只有三个,不难想到取中间值作为根节点,最小值为左节点,最大值是右节点。如果数组元素超过三个,因为数组是有序的,我们可以递归地创建这颗平衡二叉搜索树。数组中间元素 mid 作为根节点,mid 左边的数组元素作为左子树,mid 右边的数组元素作为右子树, 递归结束的条件是 左边界大于右边界时

2.2 图解

三、题解

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

    private TreeNode helper(int low, int high, int[] nums) {
        if (low > high) {
            return null;
        }
        int mid = (low + high) >> 1;
        // 根节点
        TreeNode root = new TreeNode(nums[mid]);
        // 构造左子树
        root.left = helper(low, mid - 1, nums);
        // 构造右子树
        root.right = helper(mid + 1, high, nums);
        return root;
    }
}