Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

[LeetCode Road] Convert Sorted Array to Binary Search Tree - Solution/C++

108. Convert Sorted Array to Binary Search Tree

Question:

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

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.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
    0
   / \
  -3  9
  /  /
 -10 5

Source code

Version 1

Idea:
At first, let we understand "What is Height Balanced Binary Search Tree(BST)". You inquire/insert/delete a node of the tree, the time of these actions is proportional to height of the tree. It must keeps its height in the face of arbitrary item (actions), it's call a height balane (or self balancing) BST.

Back to this problem, the strategy is "Binary Search". At 22 line, the recursive function always satisfy the establishment of the left nodes. On the contrary, it always satisfy the establishment of hte right nodes at 23 line. Using the binary search will through every nodes and get a sequential array.

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return sortedArrayToBST(nums, 0, nums.size() - 1);
}
private:
TreeNode* sortedArrayToBST(vector<int>& nums, int left, int right){
if(left > right) return NULL;
int mid = left + (right - left)/2;
TreeNode* res = new TreeNode(nums[mid]);
res->left = sortedArrayToBST(nums, left, mid - 1);
res->right = sortedArrayToBST(nums, mid + 1, right);
return res;
}
};
Each steps info.:

left:0, right:4, mid's value:0
left:0, right:1, mid's value:-10
left:0, right:-1, return NULL
left:1, right:1, mid's value:-3
left:1, right:0, return NULL
left:2, right:1, return NULL
left:3, right:4, mid's value:5
left:3, right:2, return NULL
left:4, right:4, mid's value:9
left:4, right:3, return NULL
left:5, right:4, return NULL