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 | /** |
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