-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathProblem_22.java
More file actions
90 lines (77 loc) · 2.6 KB
/
Copy pathProblem_22.java
File metadata and controls
90 lines (77 loc) · 2.6 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
85
86
87
88
89
90
// Flatten BST to sorted list
class Problem_22 {
// A binary tree node
static class Node {
int data;
Node left, right;
Node(int item) {
data = item;
left = right = null;
}
}
Node root;
// Function to insert a new node with given key in BST
static Node insert(Node node, int key) {
// If the tree is empty, return a new node
if (node == null) {
return new Node(key);
}
// Otherwise, recur down the tree
if (key < node.data) {
node.left = insert(node.left, key);
} else {
node.right = insert(node.right, key);
}
return node;
}
// Function to perform in-order traversal and store nodes in a list
static void inorderTraversal(Node node, java.util.List<Node> nodeList) {
if (node == null) {
return;
}
inorderTraversal(node.left, nodeList);
nodeList.add(node);
inorderTraversal(node.right, nodeList);
}
// Function to flatten the BST to a sorted linked list
static Node flattenBSTToSortedList(Node root) {
java.util.List<Node> nodeList = new java.util.ArrayList<>();
inorderTraversal(root, nodeList);
// Re-link nodes to form a sorted linked list
for (int i = 0; i < nodeList.size() - 1; i++) {
Node current = nodeList.get(i);
Node next = nodeList.get(i + 1);
current.left = null; // Set left child to null
current.right = next; // Set right child to next node
}
// Handle the last node
if (!nodeList.isEmpty()) {
Node lastNode = nodeList.get(nodeList.size() - 1);
lastNode.left = null;
lastNode.right = null;
}
// Return the head of the sorted linked list
return nodeList.isEmpty() ? null : nodeList.get(0);
}
// Utility function to print the sorted linked list
static void printSortedList(Node head) {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.right;
}
System.out.println();
}
public static void main(String[] args) {
Problem_22 tree = new Problem_22();
tree.root = insert(tree.root, 5);
insert(tree.root, 3);
insert(tree.root, 7);
insert(tree.root, 2);
insert(tree.root, 4);
insert(tree.root, 6);
insert(tree.root, 8);
Node sortedListHead = flattenBSTToSortedList(tree.root);
printSortedList(sortedListHead);
}
}