Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
转载于https://discuss.leetcode.com/topic/8141/share-my-o-1-space-and-o-n-time-java-code
思想:因为是排好序的,这里借助中序遍历的思想,依次遍历,生成BST,后面看到另一种更容易理解的方法。先用快慢指针找到链表的中点前的那个节点,
即……->slow->mid->mid->next;这里你得到slow指向mid的前一节点。mid是数的根节点,先生成右子树,然后使得slow->next=NULL,切断链表,再生成左子树。
借助中序遍历:
class Solution {
ListNode* node;
TreeNode* inorderhelper(int start,int end)
{
if(start>end)
return NULL;
int mid=start+(end-start)/2;
TreeNode* left=inorderhelper(start,mid-1);
TreeNode* treenode=new TreeNode(node->val);
treenode->left=left;
node=node->next;
TreeNode* right=inorderhelper(mid+1,end);
treenode->right=right;
return treenode;
}
public:
TreeNode* sortedListToBST(ListNode* head) {
if(!head)
return NULL;
int size=0;
ListNode *runner=head;
node=head;
while(runner!=NULL)
{
size++;
runner=runner->next;
}
return inorderhelper(0,size-1);
}
};
第二种:
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(!head)
return NULL;
if(!head->next)
return new TreeNode(head->val);
ListNode*slow=head,*fast=head->next->next;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
}
TreeNode*right=sortedListToBST(slow->next->next);
TreeNode* root=new TreeNode(slow->next->val);
root->right=right;
slow->next=NULL;//important
TreeNode* left=sortedListToBST(head);
root->left=left;
return root;
}
};