Convert Sorted List to Binary Search Tree
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
ListNode* cut(ListNode* A) { ListNode* slow = A; ListNode* fast = A; ListNode* prev = slow; while(fast->next and fast->next->next) { prev = slow; slow = slow->next; fast = fast->next->next; } return prev; } TreeNode* Solution::sortedListToBST(ListNode* A) { if(A == NULL) return NULL; if(A->next == NULL) return new TreeNode(A->val); ListNode* now = cut(A); TreeNode* res = new TreeNode(now->next->val); ListNode* right = now->next->next; ListNode* left = A; now->next->next = NULL; now->next = NULL; res->left = sortedListToBST(left); if(right != NULL) res->right = sortedListToBST(right); return res; }
|