1、题目描述
2、题目描述
使用快慢指针寻找链表中间值。
3、代码
1 TreeNode* sortedListToBST(ListNode* head) { 2 if (head == NULL) 3 return NULL; 4 5 ListNode *mid = findmid(head); 6 7 TreeNode *node = new TreeNode(mid->val); 8 9 if (head == mid) 10 return node; 11 12 node->left = sortedListToBST(head); 13 node->right = sortedListToBST(mid->next); 14 return node; 15 16 } 17 18 19 20 ListNode *findmid(ListNode* left) 21 { 22 ListNode *preptr = NULL; 23 ListNode *slow = left; 24 ListNode *fast = left; 25 26 while (fast != NULL && fast->next != NULL) { 27 preptr = slow; 28 slow = slow->next; 29 fast = fast->next; 30 fast = fast->next; 31 } 32 if (preptr != NULL) 33 preptr->next = NULL; 34 return slow; 35 } 36