【Lintcode】1359. Convert Sorted Array to Binary Search Tree

题目地址:

https://www.lintcode.com/problem/convert-sorted-array-to-binary-search-tree/description

给定一个从小到大排序好的数组,将其转化为一个BST。

思路是分治法,先将数组一分为三,分别为左中右,中只含有一个节点作为树根,然后递归建左子树和右子树,然后接在root上即可。代码如下:

public class Solution {
    /**
     * @param nums: the sorted array
     * @return: the root of the tree
     */
    public TreeNode convertSortedArraytoBinarySearchTree(int[] nums) {
        // Write your code here.
        return buildRoot(nums, 0, nums.length - 1);
    }
    
    private TreeNode buildRoot(int[] nums, int l, int r) {
        if (l > r) {
            return null;
        }
        
        int m = l + (r - l >> 1);
        TreeNode root = new TreeNode(nums[m]);
        root.left = buildRoot(nums, l, m - 1);
        root.right = buildRoot(nums, m + 1, r);
        return root;
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) {
        val = x;
    }
}

时间复杂度 O ( n ) O(n) ,空间 O ( log n ) O(\log n) (递归栈深度,最终返回的树本身不算)。

发布了387 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105465715
今日推荐