与上一题相同。
class Solution { public: int calLen(ListNode *node) { int len = 0; while(node) { len++; node = node->next; } return len; } void createTree(ListNode *node, int start, int end, TreeNode *&tmpRoot) { if (start > end) return; int mid = (start + end) / 2; ListNode *p = node; for(int i = start; i < mid; i++) p = p->next; tmpRoot = new TreeNode(p->val); createTree(node, start, mid - 1, tmpRoot->left); createTree(p->next, mid + 1, end, tmpRoot->right); } TreeNode *sortedListToBST(ListNode *head) { int len = calLen(head); TreeNode *tmpRoot; createTree(head, 0, len - 1, tmpRoot); return tmpRoot; } };