Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.
Example:
Given sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5],which represents the following tree:
0
/ \
-3 9
/ /
-10 5
Solutions
Solution 1: Recursion
Thinking
A sorted array must become a minimum-height BST. Always picking the smallest or largest key yields a chain of height \(n\).
Height is minimized when the two subtrees are as equal in size as possible, so the root should be the midpoint of the range.
\(dfs(l,r)\) returns null when \(l>r\), otherwise builds the node at \(mid=(l+r)//2\). Inorder matches the array, so the tree is a BST of height \(\Theta(\log n)\).
We design a function dfs(l, r), which constructs a subtree from l to r. Therefore, the answer is dfs(0, len(nums) - 1).
The execution process of the function dfs(l, r) is as follows:
If l > r, return None.
Otherwise, we calculate the middle position mid = (l + r) / 2, then construct the root node, the left subtree is dfs(l, mid - 1), and the right subtree is dfs(mid + 1, r).
Finally, return the root node.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the length of the array.
1 2 3 4 5 6 7 8 91011121314151617
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution:defsortedArrayToBST(self,nums:List[int])->TreeNode:defdfs(l:int,r:int)->TreeNode:ifl>r:returnNonemid=(l+r)>>1returnTreeNode(nums[mid],dfs(l,mid-1),dfs(mid+1,r))returndfs(0,len(nums)-1)
1 2 3 4 5 6 7 8 910111213141516171819202122232425
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution{privateint[]nums;publicTreeNodesortedArrayToBST(int[]nums){this.nums=nums;returndfs(0,nums.length-1);}privateTreeNodedfs(intl,intr){if(l>r){returnnull;}intmid=(l+r)>>1;returnnewTreeNode(nums[mid],dfs(l,mid-1),dfs(mid+1,r));}}
1 2 3 4 5 6 7 8 910111213141516171819202122
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */classSolution{public:TreeNode*sortedArrayToBST(vector<int>&nums){autodfs=[&](thisauto&&dfs,intl,intr)->TreeNode*{if(l>r){returnnullptr;}intmid=l+r>>1;returnnewTreeNode(nums[mid],dfs(l,mid-1),dfs(mid+1,r));};returndfs(0,nums.size()-1);}};
1 2 3 4 5 6 7 8 91011121314151617181920
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcsortedArrayToBST(nums[]int)*TreeNode{vardfsfunc(int,int)*TreeNodedfs=func(l,rint)*TreeNode{ifl>r{returnnil}mid:=(l+r)>>1return&TreeNode{nums[mid],dfs(l,mid-1),dfs(mid+1,r)}}returndfs(0,len(nums)-1)}