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.
题意:给定一个有序的单向链表,将其转换成平衡的二叉搜索树。
思路:二分法+快慢指针
- 通过快慢指针找到根节点(链表中间节点)
- 左边部分用来构建左子树,右边部分用来构建右子树,然后递归链表左边部分和右边部分。
代码实现1:
class Solution { public: // find middle element of the list ListNode *getmiddleList(ListNode *left,ListNode *right){ //omit the condition : left!=right && left->next!=right ListNode *pre,*last; pre=left; last =left->next; while(last!=right){ last = last->next; if(last!=right){ last = last->next; pre=pre->next; } } return pre; } // retri-BST constructor TreeNode *getBST(ListNode *left,ListNode *right){ TreeNode *root = new TreeNode(0); //no leaf if(left==right) return NULL; // only one leaf if(left->next == right){ root->val=left->val; return root; } //more than one leaf ListNode *middle =getmiddleList(left,right); root->val = middle->val; root->left = getBST(left, middle); root->right = getBST(middle->next,right); return root; } TreeNode *sortedListToBST(ListNode *head) { TreeNode* root= new TreeNode(0); if(head==NULL) return NULL; if(head->next==NULL){ root->val=head->val; root->left=root->right=NULL; return root; } ListNode *left,*middle,*right; middle=left=head; right=head->next; while(right){ right=right->next; if(right){ right=right->next; middle=middle->next; } } root->val=middle->val; root->left = getBST(left, middle); root->right= getBST(middle->next,right); return root; } };
代码实现2(不使用快慢指针):
class Solution { public: TreeNode* make(ListNode* head, int low, int high) { if(low > high) return NULL; int mid = (low + high) / 2; ListNode *p = head; for(int i=low; i <mid; i++) { p = p->next; } TreeNode *root = new TreeNode(p->val); root->left = make(head, low, mid-1); root->right = make(p->next, mid+1, high); return root; } TreeNode* sortedListToBST(ListNode* head) { int n = 0; ListNode *p = head; while(p) { n++; p = p->next; } return make(head, 0, n-1); } };