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

Commit230dead

Browse files
author
applewjg
committed
first commit Convert Sorted List to Binary Search Tree
1 parent63d27d6 commit230dead

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 12, 2014
4+
Problem: Convert Sorted List to Binary Search Tree
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
7+
Notes:
8+
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
9+
10+
Solution: Recursion. Pre-order. O(n)
11+
*/
12+
/**
13+
* Definition for singly-linked list.
14+
* public class ListNode {
15+
* int val;
16+
* ListNode next;
17+
* ListNode(int x) { val = x; next = null; }
18+
* }
19+
*/
20+
/**
21+
* Definition for binary tree
22+
* public class TreeNode {
23+
* int val;
24+
* TreeNode left;
25+
* TreeNode right;
26+
* TreeNode(int x) { val = x; }
27+
* }
28+
*/
29+
publicclassSolution {
30+
publicTreeNodesortedListToBST(ListNodehead) {
31+
returnsortedListToBSTRe(head,null);
32+
}
33+
publicTreeNodesortedListToBSTRe(ListNodestart,ListNodeend) {
34+
if(start ==end)returnnull;
35+
ListNodepre =null;
36+
ListNodeslow =start;
37+
ListNodefast =start;
38+
while (fast!=end&&fast.next!=end) {
39+
fast =fast.next.next;
40+
slow =slow.next;
41+
}
42+
TreeNodenode =newTreeNode(slow.val);
43+
node.left =sortedListToBSTRe(start,slow);
44+
node.right =sortedListToBSTRe(slow.next,end);
45+
returnnode;
46+
}
47+
publicTreeNodesortedListToBST_2(ListNodehead) {
48+
if (head ==null)returnnull;
49+
if (head.next==null)returnnewTreeNode(head.val);
50+
ListNodeslow =head;
51+
ListNodefast =head;
52+
ListNodepre =null;
53+
while(fast.next!=null &&fast.next.next!=null) {
54+
pre =slow;
55+
slow =slow.next;
56+
fast =fast.next.next;
57+
}
58+
fast =slow.next;
59+
TreeNodenode =newTreeNode(slow.val);
60+
if(pre!=null) {
61+
pre.next =null;
62+
node.left =sortedListToBST(head);
63+
}
64+
node.right =sortedListToBST(fast);
65+
returnnode;
66+
}
67+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp