Skip to content

Commit

Permalink
Convert Sorted Array to Binary Search Tree.
Browse files Browse the repository at this point in the history
  • Loading branch information
AnnieKim committed Apr 9, 2013
1 parent 4a5bf13 commit 2489426
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions ConvertSortedArraytoBinarySearchTree.h
@@ -0,0 +1,39 @@
/*
Author: Annie Kim, anniekim.pku@gmail.com
Date: Apr 9, 2013
Problem: Convert Sorted Array to Binary Search Tree
Difficulty: Easy
Source: http://leetcode.com/onlinejudge#question_108
Notes:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Solution: Recursion.
*/

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
return buildBST(num, 0, num.size() - 1);
}

TreeNode *buildBST(vector<int> &num, int start, int end)
{
if (start > end) return NULL;

int mid = (start + end) / 2;
TreeNode *root = new TreeNode(num[mid]);
root->left = buildBST(num, start, mid - 1);
root->right = buildBST(num, mid + 1, end);

return root;
}
};

0 comments on commit 2489426

Please sign in to comment.