Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit05818e9

Browse files
author
applewjg
committed
update
1 parent230dead commit05818e9

File tree

1 file changed

+31
-9
lines changed

1 file changed

+31
-9
lines changed

‎ConvertSortedListtoBinarySearchTree.java

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@
77
Notes:
88
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
99
10-
Solution: Recursion. Pre-order. O(n)
10+
Solution: 1. Recursion. In-order. O(n)
11+
2. Recursion . Pre-order.
12+
3. pre-order.
1113
*/
1214
/**
1315
* Definition for singly-linked list.
@@ -27,10 +29,30 @@
2729
* }
2830
*/
2931
publicclassSolution {
30-
publicTreeNodesortedListToBST(ListNodehead) {
31-
returnsortedListToBSTRe(head,null);
32+
publicListNodeiter;
33+
publicTreeNodesortedListToBST_1(ListNodehead) {
34+
iter =head;
35+
intlen =0;
36+
while (head !=null) {
37+
++len;
38+
head =head.next;
39+
}
40+
returnsortedListToBSTRe1(len);
41+
}
42+
publicTreeNodesortedListToBSTRe1(intlen) {
43+
if (len ==0)returnnull;
44+
intmid =len /2;
45+
TreeNodeleft =sortedListToBSTRe1(mid);
46+
TreeNoderoot =newTreeNode(iter.val);
47+
root.left =left;
48+
iter =iter.next;
49+
root.right =sortedListToBSTRe1(len -1 -mid);
50+
returnroot;
3251
}
33-
publicTreeNodesortedListToBSTRe(ListNodestart,ListNodeend) {
52+
publicTreeNodesortedListToBST_2(ListNodehead) {
53+
returnsortedListToBSTRe2(head,null);
54+
}
55+
publicTreeNodesortedListToBSTRe2(ListNodestart,ListNodeend) {
3456
if(start ==end)returnnull;
3557
ListNodepre =null;
3658
ListNodeslow =start;
@@ -40,11 +62,11 @@ public TreeNode sortedListToBSTRe(ListNode start, ListNode end) {
4062
slow =slow.next;
4163
}
4264
TreeNodenode =newTreeNode(slow.val);
43-
node.left =sortedListToBSTRe(start,slow);
44-
node.right =sortedListToBSTRe(slow.next,end);
65+
node.left =sortedListToBSTRe2(start,slow);
66+
node.right =sortedListToBSTRe2(slow.next,end);
4567
returnnode;
4668
}
47-
publicTreeNodesortedListToBST_2(ListNodehead) {
69+
publicTreeNodesortedListToBST_3(ListNodehead) {
4870
if (head ==null)returnnull;
4971
if (head.next==null)returnnewTreeNode(head.val);
5072
ListNodeslow =head;
@@ -59,9 +81,9 @@ public TreeNode sortedListToBST_2(ListNode head) {
5981
TreeNodenode =newTreeNode(slow.val);
6082
if(pre!=null) {
6183
pre.next =null;
62-
node.left =sortedListToBST(head);
84+
node.left =sortedListToBST_3(head);
6385
}
64-
node.right =sortedListToBST(fast);
86+
node.right =sortedListToBST_3(fast);
6587
returnnode;
6688
}
6789
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp