# Convert Sorted Array to Binary Search Tree

Source: Internet
Author: User

Convert Sorted Array to Binary Search Tree

Problem:

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

Ideas:

Recursive, DFS

My Code:

`/*** Definition for Binary tree * public class TreeNode {* Int. val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode Sortedarraytobst (int[] num) {        if(num = =NULL|| Num.length = = 0 )            return NULL ; intLen =num.length; TreeNode rst= Arraytobst (num, 0, len-1); returnrst; }     PublicTreeNode Arraytobst (int[] num,intLeftintRight ) {        if(Left > right)return NULL; if(left = right)return NewTreeNode (Num[left]); intMid = (left + right)/2; TreeNode Root=NewTreeNode (Num[mid]); Root.left= Arraytobst (num, left, mid-1); Root.right= Arraytobst (num, mid + 1, right); returnRoot; }}`
View Code

Others code:

` PublicTreeNode Sortedarraytobst (int[] num) {    if(Num.length = = 0) {        return NULL; } TreeNode head= Helper (num, 0, num.length-1); returnhead;} PublicTreeNode Helper (int[] num,intLowintHigh ) {    if(Low > High) {// Done        return NULL; }    intMid = (low + high)/2; TreeNode node=NewTreeNode (Num[mid]); Node.left= Helper (num, Low, mid-1); Node.right= Helper (num, mid + 1, high); returnnode;}`
View Code

The Learning Place:

• My code has redundancy where left = = Right judgment can be omitted

Convert Sorted Array to Binary Search Tree

Related Keywords:

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.