首页 > 代码库 > Leetcode#109 Convert Sorted List to Binary Search Tree

Leetcode#109 Convert Sorted List to Binary Search Tree

原题地址

 

跟Convert Sorted Array to Binary Search Tree(参见这篇文章)类似,只不过用list就不能随机访问了。

 

代码:

 1 TreeNode *buildBST(ListNode *head, int len) { 2   if (len <= 0) 3     return NULL; 4  5   ListNode *p = head; 6   int leftLen = 1; 7   while (leftLen * 2 < len) { 8     p = p->next; 9     leftLen++;10   }11   TreeNode *node = new TreeNode(p->val);12   node->left = buildBST(head, leftLen - 1);13   node->right = buildBST(p->next, len - leftLen);14 15   return node;16 }17 18 TreeNode *sortedListToBST(ListNode *head) {19   ListNode *node = head;20   int len = 0;21 22   while (node) {23     node = node->next;24     len++;25   }26   return buildBST(head, len);27 }

 

Leetcode#109 Convert Sorted List to Binary Search Tree