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

Title address:

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

Given a sorted array from small to large, convert it into a BST.

The idea is to divide and conquer, first divide the array into three, which are left, middle and right, which contains only one node as the root of the tree, and then recursively build the left and right subtrees, and then connect to the root. code show as below:

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;
    }
}

time complexity THE ( n ) O (n) , space THE ( log n ) O(\log n) (recursive stack depth, the final returned tree does not count itself).

Published 387 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105465715