Skip to content

Commit 2e4c572

Browse files
committed
refine
1 parent d60cbc7 commit 2e4c572

File tree

2 files changed

+25
-34
lines changed

2 files changed

+25
-34
lines changed

BalancedBinaryTree.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11

2-
32
/**
43
* Given a binary tree, determine if it is height-balanced.
54
*
6-
* For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
5+
* For this problem, a height-balanced binary tree is defined as a binary tree
6+
* in which the depth of the two subtrees of every node never differ by more
7+
* than 1.
78
*
89
*/
910

ConvertSortedListtoBinarySearchTree.java

Lines changed: 22 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -6,36 +6,26 @@
66

77
public class ConvertSortedListtoBinarySearchTree {
88
public TreeNode sortedListToBST(ListNode head) {
9-
ListNode n = head;
10-
int size = 0;
11-
while (n != null) {
12-
size++;
13-
n = n.next;
14-
}
15-
int[] num = new int[size];
16-
n = head;
17-
int i = 0;
18-
while (n != null) {
19-
num[i++] = n.val;
20-
n = n.next;
21-
}
22-
return sortedArrayToBST(num);
23-
}
24-
25-
public TreeNode sortedArrayToBST(int[] num) {
26-
return sortedArrayToBST(num, 0, num.length - 1);
27-
}
28-
29-
public TreeNode sortedArrayToBST(int[] num, int start, int end) {
30-
if (start <= end) {
31-
int mid = (start + end) / 2;
32-
TreeNode left = sortedArrayToBST(num, start, mid - 1);
33-
TreeNode right = sortedArrayToBST(num, mid + 1, end);
34-
TreeNode node = new TreeNode(num[mid]);
35-
node.left = left;
36-
node.right = right;
37-
return node;
38-
}
39-
return null;
40-
}
9+
return sortedListToBST(head, null);
10+
}
11+
12+
private TreeNode sortedListToBST(ListNode start, ListNode end) {
13+
if (start == end) {
14+
return null;
15+
} else if (start.next == end) {
16+
return new TreeNode(start.val);
17+
} else {
18+
ListNode fast = start, slow = start;
19+
while (fast.next != end && fast.next.next != end) {
20+
fast = fast.next.next;
21+
slow = slow.next;
22+
}
23+
TreeNode left = sortedListToBST(start, slow);
24+
TreeNode right = sortedListToBST(slow.next, end);
25+
TreeNode root = new TreeNode(slow.val);
26+
root.left = left;
27+
root.right = right;
28+
return root;
29+
}
30+
}
4131
}

0 commit comments

Comments
 (0)