Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:
递归
代码:
1 TreeNode *sortedListToBST(ListNode *head, int len){ 2 if(len == 0){ 3 return NULL; 4 } 5 TreeNode *result = new TreeNode(0); 6 if(len == 1){ 7 result->val = head->val; 8 return result; 9 } 10 ListNode *listNode = head; 11 for(int i = 0; i < len/2; i++) 12 listNode = listNode->next; 13 result->val = listNode->val; 14 result->left = sortedListToBST(head, len/2); 15 result->right = sortedListToBST(listNode->next, (len-1)/2); 16 return result; 17 } 18 TreeNode *sortedListToBST(ListNode *head) { 19 // IMPORTANT: Please reset any member data you declared, as 20 // the same Solution instance will be reused for each test case. 21 if(head == NULL) 22 return NULL; 23 ListNode *listNode = head; 24 int len = 0; 25 while(listNode){ 26 len++; 27 listNode = listNode->next; 28 } 29 return sortedListToBST(head, len); 30 }