-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertSortedList2BinarySearchTree_109.java
More file actions
42 lines (38 loc) · 1.18 KB
/
ConvertSortedList2BinarySearchTree_109.java
File metadata and controls
42 lines (38 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/************************************************************
* $$$$$$$$$$$$$ This is a very good way to learn recursion,
* Because, the way of the order is each to the in-order traversal of the tree
*/
public class Solution {
ListNode head = null;
public TreeNode sortedListToBST(ListNode head) {
ListNode curr = head; int length = 0;
while (curr != null) { length++; curr = curr.next; }
this.head = head;
return sortedListToBST(0, length);
}
public TreeNode sortedListToBST(int l, int r) {
if (l >= r) return null;
TreeNode left = sortedListToBST(l, (l+r)/2);
TreeNode parent = new TreeNode(head.val);
parent.left= left; head = head.next; // head will not equal to null;
parent.right = sortedListToBST((l+r)/2+1, r);
return parent;
}
}