[编程题]convert-sorted-list-to-binary-search-tree
时间限制:1秒 空间限制:32768K
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:
二分查找法每次需要找到中间元素所在节点,而链表的查找中间点
可以通过快慢指针来操作。找到中点后,要以中点的值建立
二叉搜索树的的根节点,然后需要把原链表断开,分为前后两个链表,
分别连上左右子节点即可。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
return CreatBinarySearchTree(head,NULL);
}
TreeNode *CreatBinarySearchTree(ListNode *head,ListNode *tail){
if(head == tail) return NULL;
ListNode *pSlower = head;
ListNode *pFaster = head;
while(pFaster!=tail && pFaster->next!=tail){
pSlower = pSlower->next;
pFaster = pFaster->next->next;
}
TreeNode *BSTroot = new TreeNode(pSlower->val);
BSTroot->left = CreatBinarySearchTree(head,pSlower);
BSTroot->right = CreatBinarySearchTree(pSlower->next,tail);
return BSTroot;
}
};
这个是网上看到的解法基本同理我觉得更好理解一点,可读性更高
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
if(head==NULL) return NULL;
ListNode *pFaster=head,*pSlower=head,*prev=NULL;
while(pFaster!=NULL&&pFaster->next!=NULL){
pFaster=pFaster->next->next;
prev=pSlower;
pSlower=pSlower->next;
}
TreeNode *root=new TreeNode(pSlower->val);
if(prev!=NULL){
prev->next=NULL;
root->left=sortedListToBST(head);
}
if(pSlower->next!=NULL){
root->right=sortedListToBST(pSlower->next);
}
return root;
}
};