思路
使用快慢指针,每次将中间节点当做根节点,一部分是左节点,一部分是右节点,然后递归
代码
/*** @param {ListNode} head* @return {TreeNode}*/var sortedListToBST = function(head) {// 判断边界条件if (!head) return null;if (!head.next) return new TreeNode(head.val);let pre = head, cur = pre.next, next = cur.next;while(next && next.next) {pre = pre.next;cur = pre.next;next = next.next.next;}// 断开链表pre.next = null;// 当前根节点const root = new TreeNode(cur.val);root.left = sortedListToBST(head);root.right = sortedListToBST(cur.next);return root;};
复杂度分析
时间复杂度 #card=math&code=O%28nlogN%29)
空间复杂度 #card=math&code=O%28N%29)
