-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay46.java
More file actions
84 lines (69 loc) · 1.91 KB
/
Copy pathDay46.java
File metadata and controls
84 lines (69 loc) · 1.91 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
109. Convert Sorted List to Binary Search Tree
Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.
Example 1:
Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Example 2:
Input: head = []
Output: []
Program:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
/*
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
// Base case: only one node
if (head.next == null) {
return new TreeNode(head.val);
}
// Find middle node
ListNode prev = null;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
// Cut the list into two halves
if (prev != null) {
prev.next = null;
}
// Middle becomes root
TreeNode root = new TreeNode(slow.val);
// Build left subtree
if (head != slow) {
root.left = sortedListToBST(head);
}
// Build right subtree
root.right = sortedListToBST(slow.next);
return root;
}
}
*/