Old discuss is read-only now. Please go to New LeetCode Discuss for your questions and answers!

User account in old discuss will not integrate to the new one, but new discuss is integrated with new online judge, which means, if you already have an account in new online judge, you can access new discuss immediately!

If you want to ask for question relevant to the posts in old discuss, please copy content as part of your question, only old discuss link is NOT ALLOWED!

Please read the FAQ in new LeetCode Discuss to help yourself making the best use of Discuss!

0
1

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

asked 25 Nov '10, 15:06

1337c0d3r's gravatar image

1337c0d3r ♦♦
1.2k1384171
accept rate: 2%


Hint:
This question is highly recursive in nature. Think of how binary search works.


An example of a height-balanced tree. A height-balanced tree is a tree whose subtrees differ in height by no more than one and the subtrees are height-balanced, too.

Solution:
If you would have to choose an array element to be the root of a balanced BST, which element would you pick? The root of a balanced BST should be the middle element from the sorted array.

You would pick the middle element from the sorted array in each iteration. You then create a node in the tree initialized with this element. After the element is chosen, what is left? Could you identify the sub-problems within the problem?

There are two arrays left -- The one on its left and the one on its right. These two arrays are the sub-problems of the original problem, since both of them are sorted. Furthermore, they are subtrees of the current node's left and right child.

The code below creates a balanced BST from the sorted array in O(N) time (N is the number of elements in the array). Compare how similar the code is to a binary search algorithm. Both are using the divide and conquer methodology.

BinaryTree* sortedArrayToBST(int arr[], int start, int end) {
    if (start > end) return NULL;
    // same as (start+end)/2, avoids overflow.
    int mid = start + (end - start) / 2;
    BinaryTree *node = new BinaryTree(arr[mid]);
    node->left = sortedArrayToBST(arr, start, mid-1);
    node->right = sortedArrayToBST(arr, mid+1, end);
    return node;
}

BinaryTree* sortedArrayToBST(int arr[], int n) {
    return sortedArrayToBST(arr, 0, n-1);
}

Further Thoughts:
Consider changing the problem statement to "Converting a singly linked list to a balanced BST". How would your implementation change from the above?

Check out my next post: Convert Sorted List to Balanced Binary Search Tree (BST) for the best solution.

link

answered 25 Nov '10, 15:06

1337c0d3r's gravatar image

1337c0d3r ♦♦
1.2k1384171
accept rate: 2%

Use recursive method to solve this question.

TreeNode *sortedArrayToBST(vector<int> &num) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    if (num.size() == 0) {
        return NULL;
    }

    if (num.size() == 1) {
        TreeNode *root = new TreeNode(num[0]);
        return root;
    }

    std::vector<int> left_tree(num.begin(), num.begin() + num.size()/2);
    std::vector<int> right_tree(num.begin() + num.size()/2 + 1, num.end());

    TreeNode *root = new TreeNode(num[num.size()/2]);
    root->left = sortedArrayToBST(left_tree);
    root->right = sortedArrayToBST(right_tree);

    return root;
}
link

answered 07 Mar '13, 21:56

whitebluff's gravatar image

whitebluff
212
accept rate: 0%

use recursive function

TreeNode *sortedArrayToBST(vector<int> &num) {
    return helper(num, 0, num.size());
}
TreeNode *helper(vector<int> &num, int start, int end) {
    int M = end-start;
    if (M < 1) {
        return NULL;
    } else if(M ==1) {
        return new TreeNode(num[start]);
    } 
    TreeNode* root = new TreeNode(num[start+M/2]);
    TreeNode* left = helper(num, start, start+M/2);
    TreeNode* right = helper(num, start+M/2+1, end);
    root->left = left;
    root->right = right;
    return root;
}
link

answered 22 Apr '13, 09:58

monsoonzeng's gravatar image

monsoonzeng
1
accept rate: 0%

class Solution {
public:
    TreeNode *sortedArrayToBST(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function

        int len = num.size();
        TreeNode *root;
        if(len==0)return NULL;
        if(len==1){root=new TreeNode(num[0]);return root;}
        return DFS(0,len-1,root,num);
    }
    TreeNode *DFS(int left,int right,TreeNode *root,vector<int> &num)
    {
        if(left>right)
        {
            return NULL;
        }
        if(left==right)
        {
            root = new TreeNode(num[left]);
            return root;
        }
        int mid = left+((right-left)>>1);
        root = new TreeNode(num[mid]);
        if(left<mid)root->left = DFS(left,mid-1,root->left,num);
        if(mid<right)root->right = DFS(mid+1,right,root->right,num);
        return root;
    }
};
link
This answer is marked "community wiki".

answered 02 May '13, 04:14

sillyjims's gravatar image

sillyjims
9614
accept rate: 0%

public class Solution {

public TreeNode sortedArrayToBST(int[] num) {
    if (num.length == 0) return null;
    return toBST(num,0,num.length-1);
}

private TreeNode toBST(int[] num,int s, int e){
    TreeNode res = new TreeNode(0);        
    if(s==e)
        return new TreeNode(num[s]);
    else if(e-s == 1){ //Case for two elements
        res.val = num[e];
        res.left = new TreeNode(num[s]);
    }else if( (e-s)%2 == 0){ //Case for odd number elements
        res.val = num[(e+s)/2];
        res.left = toBST(num,s,(e+s -2)/2 );
        res.right = toBST(num,(e+s +2)/2,e);
    } else{ //Case for even number elements
        res.val = num[(e+s+1)/2];
        res.left = toBST(num,s,(e+s-1)/2);
        res.right = toBST(num,(e+s+3)/2,e);
    }
    return res;
}

}

link

answered 06 Jun '13, 14:34

lfgao's gravatar image

lfgao
1
accept rate: 0%

TreeNode *sortedArrayToBST(vector<int> &num) {

    if(num.size() == 0) {
       return NULL;
    }
    if(num.size() == 1) {
        return new TreeNode(num[0]);
    }
    int middle = num.size()/2;
    TreeNode *root = new TreeNode(num[middle]);
    vector<int> left(num.begin(), num.begin() + middle );
    vector<int> right(num.begin() + middle + 1 , num.end());
    root->left = sortedArrayToBST(left);
    root->right = sortedArrayToBST(right);
    return root;
}
link

answered 23 Jul '13, 17:53

romo's gravatar image

romo
11
accept rate: 0%

edited 23 Jul '13, 17:54

class Solution {
public:
    TreeNode* CreateNode(vector<int>& num, int lo, int hi)
    {
        if (lo == hi)
        {
            return new TreeNode(num[lo]);
        }
        int mid = lo + ((hi-lo) / 2);
        TreeNode* root = new TreeNode(num[mid]);
        if (mid-1 >= lo)
        {
            root->left = CreateNode(num, lo, mid-1);
        }
        if (mid + 1 < num.size())
        {
            root->right = CreateNode(num, mid+1, hi);
        }
        return root;
    }

    TreeNode* sortedArrayToBST(vector<int> &num)
    {
        if (0 == num.size())
        {
            return NULL;
        }
        TreeNode* root = CreateNode(num, 0, num.size()-1);
        return root;
    }
};
link

answered 15 Aug '13, 19:49

zakcoder's gravatar image

zakcoder
112
accept rate: 0%

public TreeNode sortedArrayToBST(int[] num) {
    if( num.length < 1 ){
        return null;
    }
    int mid = (int) num.length/2;
    TreeNode root = new TreeNode( num[mid] );
    root.left = sortedArrayToBST(Arrays.copyOfRange(num, 0, mid));
    root.right = sortedArrayToBST(Arrays.copyOfRange(num,mid+1,num.length));
    return root;
}
link

answered 25 Sep '13, 02:23

wnghn's gravatar image

wnghn
112
accept rate: 0%

public static Node sortedArrayToBST(int[] input, int start, int end) 
{
    //base cases
    if (input == null || start > end)
    {
        return null;
    }

    if (start==end)
    {
        return new Node(input[start]);
    }

    int middleIndex = (start+end)/2;
    int meanVal = input[middleIndex];
    Node root = new Node(meanVal);

    root.leftChild = sortedArrayToBST(input, start, middleIndex-1);
    root.rightChild = sortedArrayToBST(input, middleIndex+1, end);

    return root;
}
link

answered 18 Oct '13, 21:11

e230217's gravatar image

e230217
213
accept rate: 0%

Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • Indent code by 4 spaces.
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×133
×28
×4

Asked: 25 Nov '10, 15:06

Seen: 1,821 times

Last updated: 18 Oct '13, 21:11