Leetcode 108.Convert Sorted Array to Binary Search Tree (convert sorted array to BST) ideas and methods for solving problems

Source: Internet
Author: User

Given an array where elements is sorted in ascending order, convert it to a height balanced BST.

Idea: Convert a sorted array into a highly balanced two-fork search tree. The idea is to use the middle value as the root node, and then the left and right arrays are the left and right sub-trees. Recursive solution.

The code is as follows:

/** * Definition for a binary tree node.  * public class TreeNode {*     int val, *     TreeNode left, *     TreeNode right; *     TreeNode (int x) {val = x;} *} */public class Solution {public TreeNode sortedarraytobst (int[] nums) {        /**         * Highly balanced binary search tree         * refers to the height difference of the left and right subtree not exceeding 1         * So every time from the middle tectonic root node * Both sides of the construction of the left and right         subtree *         /return BST (nums,0,nums.length-1);    } Private TreeNode BST (int[] nums, int i, int j) {if (i > J) {return null;} int mid = (j + i + 1)/2; TreeNode root = new TreeNode (Nums[mid]); root.left = BST (nums,i,mid-1);        Root.right = BST (nums,mid+1,j);        return root;}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 108.Convert Sorted Array to Binary Search Tree (convert sorted array to BST) ideas and methods for solving problems

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.