Convert Sorted List to Binary Search Tree
Posted Agentgamer
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Convert Sorted List to Binary Search Tree相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/#/description
跟数组那题没有什么本质区别,唯一的障碍是,在数组里因为长度已知,所以求中位数很方便。但是链表里找中位数就麻烦一点了。
快慢指针再一次登场了,快指针一次走两步,慢指针一次走一步。那么当快指针走到尽头的时候,慢指针就刚好指在链表的中间。
function ListNode(val) { this.val = val; this.next = null; } function TreeNode(val) { this.val = val; this.left = this.right = null; } /** * @param {ListNode} head * @return {TreeNode} */ var sortedListToBST = function(head) { return ct(head, null); }; function ct(head, tail) { if (!head) return null; if (head == tail) {return null;} var mid = head; var fast = head; while (fast.next !== tail && fast.next.next !== tail) { mid = mid.next; fast = fast.next.next; } var root = new TreeNode(mid.val); root.left = ct(head, mid); root.right = ct(mid.next, tail); return root; }
以上是关于Convert Sorted List to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章
109.Convert sorted list to BST
Convert Sorted List to Binary Search Tree
Convert Sorted List to Balanced BST
109. Convert Sorted List to Binary Search Tree