Convert Sorted List to Binary Search Tree
A straight method for this problem is the get the midpoint of the list, creating the root with the corresponding key, andrecursing on the first half and the second half of the list. The time complexity is T(n)=2*T(n/2) + O(n). According the master theorem, T(n) =a*T(n/b) + f(n), Thus, T(n)=O(nlogn).
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
if(head==NULL) return NULL;
if(head->next==NULL) return new TreeNode(head->val);
TreeNode *newhead=NULL;
ListNode *p1, *p2, *pre;
p2=head;
p1=head; //使得p2在中间位置的前一位
while(p1){
p1=p1->next;
if(p1){
pre=p2;
p2=p2->next;
p1=p1->next;
}
}
pre->next=NULL;
newhead=new TreeNode(p2->val);
newhead->left=sortedListToBST(head);
newhead->right=sortedListToBST(p2->next);
return newhead;
}
};
We can avoid the additional space required to convert the list to an array by the first building the tree with empty keys, and then populating (填入,增长) it by performingan inorder walk of the tree in conjunction with a traversal of the list.
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
if(head==NULL) return NULL;
ListNode *p=head;
int len=0;
while(p){++len; p=p->next; }
return sortedListToBST(head, 0, len);
}
TreeNode *sortedListToBST(ListNode* &head, int st, int ed){ //head must be a referenced type
TreeNode *cur=NULL;
if(st<ed){
cur=new TreeNode(0);
int mid=(st+ed)/2;
cur->left=sortedListToBST(head, st, mid);
cur->val=head->val;
head=head->next;
cur->right=sortedListToBST(head, mid+1, ed);
}
return cur;
}
};
The time complexity is O(n) for each node is visited only once.
Convert Sorted Array to Binary Search Tree
Directly find the midpoint of the array and creating the root with the value, and recursing on the first half and the second half of the list.
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
if(num.size()==0) return NULL;
return sortedArrayToBST(num, 0, num.size());
}
TreeNode *sortedArrayToBST(vector<int>& num, int start, int end){
TreeNode *head=NULL;
if(start<end){
int mid=(start+end)/2;
head=new TreeNode(num[mid]);
if(start<mid){
head->left=sortedArrayToBST(num, start, mid);
}
if(mid<end){
head->right=sortedArrayToBST(num, mid+1, end);
}
}
return head;
}
};