【DFS】LeetCode 108. 将有序数组转换为二叉搜索树

题目链接

108. 将有序数组转换为二叉搜索树

思路

类似于二分搜索,定位到数组中间 mid,然后左边的子数组构成左子树,右边的子数组构成右子树,mid 处的数字构成根结点。递归构建左右子树即可,最后返回 root

代码

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return buildBST(nums, 0, nums.length - 1);
    }

    public TreeNode buildBST(int[] nums, int left, int right){
        if(left > right){
            return null;
        }

        int mid = (right - left) / 2 + left;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = buildBST(nums, left, mid - 1);
        root.right = buildBST(nums, mid + 1, right);

        return root;
    }
}
posted @ 2023-02-12 19:37  Frodo1124  阅读(20)  评论(0编辑  收藏  举报