Skip to content

Commit 30f6a5c

Browse files
committed
109. 有序链表转换二叉搜索树
1 parent 15fcce9 commit 30f6a5c

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
|106|[从中序与后序遍历序列构造二叉树](https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)|[JavaScript](./algorithms/construct-binary-tree-from-inorder-and-postorder-traversal.js)|Medium|
5454
|107|[二叉树的层序遍历 II](https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/)|[JavaScript](./algorithms/binary-tree-level-order-traversal-ii.js)|Medium|
5555
|108|[将有序数组转换为二叉搜索树](https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/)|[JavaScript](./algorithms/convert-sorted-array-to-binary-search-tree.js)|Easy|
56+
|109|[有序链表转换二叉搜索树](https://leetcode.cn/problems/convert-sorted-list-to-binary-search-tree/)|[JavaScript](./algorithms/convert-sorted-list-to-binary-search-tree.js)|Medium|
5657
|110|[平衡二叉树](https://leetcode.cn/problems/balanced-binary-tree/)|[JavaScript](./algorithms/balanced-binary-tree.js)|Easy|
5758
|111|[二叉树的最小深度](https://leetcode.cn/problems/minimum-depth-of-binary-tree/)|[JavaScript](./algorithms/minimum-depth-of-binary-tree.js)|Easy|
5859
|112|[路径总和](https://leetcode.cn/problems/path-sum/)|[JavaScript](./algorithms/path-sum.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* Definition for a binary tree node.
10+
* function TreeNode(val, left, right) {
11+
* this.val = (val===undefined ? 0 : val)
12+
* this.left = (left===undefined ? null : left)
13+
* this.right = (right===undefined ? null : right)
14+
* }
15+
*/
16+
/**
17+
* @param {ListNode} head
18+
* @return {TreeNode}
19+
*/
20+
var sortedListToBST = function (head) {
21+
if (!head) return null;
22+
if (!head.next) return new TreeNode(head.val);
23+
24+
let slow = head;
25+
let fast = head;
26+
// 左边的最后一个节点
27+
let lastLeft = head;
28+
// 快慢指针找到中间节点
29+
while (fast && fast.next) {
30+
lastLeft = slow;
31+
slow = slow.next;
32+
fast = fast.next.next;
33+
}
34+
const right = slow.next;
35+
slow.next = null;
36+
lastLeft.next = null;
37+
const root = new TreeNode(slow.val);
38+
root.left = sortedListToBST(head);
39+
root.right = sortedListToBST(right);
40+
41+
return root;
42+
};

0 commit comments

Comments
 (0)