leetcode_convert_sorted_list_to_binary_search_tree 发表于 2016-11-30 难度:Medium 解题思路:采用分治的方法。在链表中找到中间节点,创建树节点,然后截断这个链表,分为两段。再分别调用函数。 代码如下: 1234567891011121314151617181920212223242526272829303132333435363738394041/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; *//** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode* sortedListToBST(ListNode* head) { if(head == NULL) return NULL; if(head->next == NULL) return new TreeNode(head->val); ListNode *dummy = new ListNode(-1); dummy->next = head; ListNode *slow = dummy; ListNode *fast = dummy; while(fast->next != NULL && fast->next->next != NULL) { slow = slow->next; fast = fast->next->next; } fast = slow->next; slow->next = NULL; TreeNode *new_node = new TreeNode(fast->val); new_node->left = sortedListToBST(head); new_node->right = sortedListToBST(fast->next); return new_node; }}; 运行结果:22ms,超过85.76%