forked from leetcoders/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertSortedArraytoBinarySearchTree.h
More file actions
39 lines (34 loc) · 991 Bytes
/
ConvertSortedArraytoBinarySearchTree.h
File metadata and controls
39 lines (34 loc) · 991 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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;
}
};