-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedlistTree
86 lines (63 loc) · 1.82 KB
/
LinkedlistTree
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
public class LinkedlistTree {
// A Binary Tree Node
static void printNodes(Node root)
{
// If node is null, return
if (root == null)
return;
// If left child exists, check for leaf
// recursively
if (root.left != null)
printNodes(root.left);
System.out.print( root.data +" ");
// If right child exists, check for leaf
// recursively
if (root.right != null)
printNodes(root.right);
}
// Function to print leaf
// nodes from left to right
static void printLeafNodes(Node root)
{
// If node is null, return
if (root == null)
return;
// If node is leaf node, print its data
if (root.left == null && root.right == null)
{
System.out.print( root.data +" ");
return;
}
// If left child exists, check for leaf
// recursively
if (root.left != null)
printLeafNodes(root.left);
// If right child exists, check for leaf
// recursively
if (root.right != null)
printLeafNodes(root.right);
}
static Node prevNode=null;
static void connectLeafs(Node root)
{
// If node is null, return
if (root == null)
return;
// If node is leaf node, print its data
if (root.left == null && root.right == null)
{
if(prevNode!=null)
prevNode.right = root;
prevNode=root;
return;
}
// If left child exists, check for leaf
// recursively
if (root.left != null)
connectLeafs(root.left);
// If right child exists, check for leaf
// recursively
if (root.right != null)
connectLeafs(root.right);
}
}