106-排序列表转换为二分查找树
给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树
样例
标签
递归 链表
思路
类似于二分查找,每次将链表二分,中间节点作为根节点,在建立左子树与右子树,递归即可
code
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: a tree node
*/
TreeNode *sortedListToBST(ListNode *head) {
// write your code here
TreeNode *root = NULL;
if(head != NULL) {
ListNode *left = NULL, *right = NULL;
root = new TreeNode(dichotomyList(head, left, right));
root->left = sortedListToBST(left);
root->right = sortedListToBST(right);
}
return root;
}
int dichotomyList(ListNode *head, ListNode *&left, ListNode *&right) {
if(head->next != NULL) {
ListNode *fast = head, *slow = head, *temp = head;
while(fast != NULL && fast->next != NULL) {
temp = slow;
slow = slow->next;
fast = fast->next->next;
}
temp->next = NULL;
left = head;
right = slow->next;
return slow->val;
}
else {
left = NULL;
right = NULL;
return head->val;
}
}
};