标签:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
[Solution]
1 TreeNode *sortedListToBST(ListNode *head) 2 { 3 int len = 0; 4 for (ListNode *visit = head; visit != NULL; visit = visit->next) 5 len++; 6 7 return BSTtranslate(head, 0, len - 1); 8 } 9 10 TreeNode *BSTtranslate(ListNode *head, int left, int right) 11 { 12 if (left > right) 13 return NULL; 14 15 int middle = (left + right) / 2; 16 ListNode *visit = head; 17 for (int i = left; i < middle; i++) 18 visit = visit->next; 19 20 TreeNode *root = new TreeNode(visit->val); 21 root->left = BSTtranslate(head, left, middle - 1); 22 root->right = BSTtranslate(visit->next, middle + 1, right); 23 24 return root; 25 }
leetcode 109. Convert Sorted List to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4293776.html