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

Posted stono

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了108. 将有序数组转换为二叉搜索树相关的知识,希望对你有一定的参考价值。

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

https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/description/

package com.test;


public class Lesson108 {
    public static void main(String[] args) {
        int[] nums = {-10,-3,0,5,9};
//        int[] nums = {0,1,2,3,4,5,6,7,8};
//        int[] nums = {0,1,2,3,4,5,6};
        TreeNode treeNode = sortedArrayToBST(nums);
        printNode(treeNode);
//        TreeNode t1 = new TreeNode(1);
//        TreeNode t2 = new TreeNode(2);
//        TreeNode t3 = new TreeNode(3);
//        t1.left = t2;
//        t1.right = t3;
//        printNode(t1);

    }
    public static TreeNode sortedArrayToBST(int[] nums) {
        int length = nums.length;
        TreeNode res = bst(0, length, nums);
        return res;
    }

    private static TreeNode bst(int start, int end, int[] nums) {
        // 如果有三个点
        if (end - start - 3 == 0) {
            TreeNode res = new TreeNode(nums[start+1]);
            TreeNode left = new TreeNode(nums[start]);
            TreeNode right = new TreeNode(nums[start+2]);
            res.left = left;
            res.right = right;
            return res;
        }
        // 如果有两个点
        if (end - start - 2 == 0) {
            TreeNode res = new TreeNode(nums[start+1]);
            TreeNode left = new TreeNode(nums[start]);
            res.left = left;
            return res;
        }
        // 如果有一个点
        if (end - start - 1 == 0) {
            TreeNode res = new TreeNode(nums[start]);
            return res;
        }
        // 没有点
        if (start - end == 0) {
            return null;
        }
        // 如果有很多点,取中间的点作为树根,左侧的点作为左树,右侧的点作为右树
        int middle = start+ (end-start)/2;
        int num = nums[middle];
        TreeNode res = new TreeNode(num);
        TreeNode left = bst(start,middle,nums);
        TreeNode right = bst(middle+1,end,nums);
        res.left = left;
        res.right = right;
        return res;
    }

    private static void printNode(TreeNode treeNode) {
        if (treeNode == null) {
            return;
        }
        // 先根
        System.out.print(treeNode.val+" ");
        if (treeNode.left != null) {
            printNode(treeNode.left);
        }
        // 中根
//        System.out.print(treeNode.val+" ");
        if (treeNode.right != null) {
            printNode(treeNode.right);
        }
    }
}

 

以上是关于108. 将有序数组转换为二叉搜索树的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode第108题—将有序数组转换为二叉搜索树—Python实现

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

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

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

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

LeetCode(108):将有序数组转换为二叉搜索树