思路:找到链表的中节点,就是二叉树的根节点,然后递归构造左右子树
链表:
TreeNode *sortedListToBST(ListNode *head) {
return ListToBST(head,NULL);
}
TreeNode* ListToBST(ListNode* head,ListNode* tail){
if(head==tail)
return NULL;
ListNode* fast=head;
ListNode* slow=head;
while(fast!=tail&&fast->next!=tail){
slow=slow->next;
fast=fast->next->next;
}
TreeNode* root=new TreeNode(slow->val);
root->left=ListToBST(head,slow);
root->right=ListToBST(slow->next,tail);
return root;
}
数组:
TreeNode *sortedArrayToBST(vector<int> &num) {
int len=num.size();
if(len==0)
return NULL;
TreeNode* root=new TreeNode(num[len/2]);
vector<int> leftNum(num.begin(),num.begin()+len/2);
vector<int> rightNum(num.begin()+len/2+1,num.end());
root->left=sortedArrayToBST(leftNum);
root->right=sortedArrayToBST(rightNum);
return root;
}
思路二:
TreeNode *sortedArrayToBST(vector<int> &num) {
return ArrayToList(num,0,num.size());
}
TreeNode* ArrayToList(vector<int> num,int start,int end){
if(start>=end)
return NULL;
int mid=(start+end)>>1;
TreeNode* root=new TreeNode(num[mid]);
root->left=ArrayToList(num,start,mid);
root->right=ArrayToList(num,mid+1,end);
return root;
}