-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlattenBtree.java
More file actions
83 lines (71 loc) · 2.58 KB
/
Copy pathFlattenBtree.java
File metadata and controls
83 lines (71 loc) · 2.58 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
package day31;
// Java program to flatten a given Binary Tree into linked list
public class FlattenBtree {
// A binary tree node
static class FNode {
int data;
FNode left, right;
FNode(int key) {
data = key;
left = right = null;
}
}
static class BinaryTre {
FNode root;
// Function to convert binary tree into linked list by
// altering the right node and making left node NULL
public void flatten(FNode node) {
// Base case - return if root is NULL
if (node == null)
return;
// Or if it is a leaf node
if (node.left == null && node.right == null)
return;
// If root.left children exists then we have to make
// it node.right (where node is root)
if (node.left != null) {
// Move left recursively
flatten(node.left);
// Store the node.right in Node named tempNode
FNode tempNode = node.right;
node.right = node.left;
node.left = null;
// Find the position to insert the stored value
FNode curr = node.right;
while (curr.right != null)
curr = curr.right;
// Insert the stored value
curr.right = tempNode;
}
// Now call the same function for node.right
flatten(node.right);
}
// Function for Inorder traversal
public void inOrder(FNode node) {
// Base Condition
if (node == null)
return;
inOrder(node.left);
System.out.print(node.data + " ");
inOrder(node.right);
}
// Driver code
public static void main(String[] args) {
BinaryTre tree = new BinaryTre();
/*
* 1 / \ 2 5 / \ \ 3 4 6
*/
tree.root = new FNode(1);
tree.root.left = new FNode(2);
tree.root.right = new FNode(5);
tree.root.left.left = new FNode(3);
tree.root.left.right = new FNode(4);
tree.root.right.right = new FNode(6);
System.out.println(
"The Inorder traversal after flattening binary tree ");
tree.flatten(tree.root);
tree.inOrder(tree.root);
}
}
// This code is contributed by Aditya Kumar (adityakumar129)
}