Skip to content

Commit 688ffc1

Browse files
authored
Create 108. Convert Sorted Array to Binary Search Tree.cpp
1 parent ea9807d commit 688ffc1

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Diff for: 108. Convert Sorted Array to Binary Search Tree.cpp

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
3+
4+
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
5+
6+
Example:
7+
8+
Given the sorted array: [-10,-3,0,5,9],
9+
10+
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
11+
12+
0
13+
/ \
14+
-3 9
15+
/ /
16+
-10 5
17+
*/
18+
/**
19+
* Definition for a binary tree node.
20+
* struct TreeNode {
21+
* int val;
22+
* TreeNode *left;
23+
* TreeNode *right;
24+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
25+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
26+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
27+
* };
28+
*/
29+
class Solution {
30+
public:
31+
TreeNode* sortedArrayToBST(vector<int>& nums) {
32+
if ( nums.empty() ) return nullptr;
33+
return convert( nums, 0, nums.size() - 1 );
34+
}
35+
TreeNode* convert( vector<int>& nums, int begin, int end )
36+
{
37+
if ( begin > end ) return nullptr;
38+
int mid = begin + ( end - begin ) / 2;
39+
TreeNode *root = new TreeNode( nums[mid] );
40+
root->left = convert( nums, begin, mid - 1 );
41+
root->right = convert( nums, mid + 1, end );
42+
return root;
43+
}
44+
};

0 commit comments

Comments
 (0)