-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathPrint_Tree_Paths.java
More file actions
83 lines (65 loc) · 1.68 KB
/
Copy pathPrint_Tree_Paths.java
File metadata and controls
83 lines (65 loc) · 1.68 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
import java.util.Scanner;
public class Print_Tree_Paths {
class Node
{
int data;
Node left;
Node right;
}
void print(int paths[], int pathLength)
{
int i;
for(i = 0; i < pathLength; i++)
System.out.print(paths[i]+" ");
System.out.print("\n");
}
void printPathsRecur(Node root, int paths[], int pathLength)
{
if (root == null)
return;
paths[pathLength++] = root.data;
if(root.left == null && root.right == null)
print(paths, pathLength);
else
{
printPathsRecur(root.left, paths, pathLength);
printPathsRecur(root.right, paths, pathLength);
}
}
void printPaths(Node root)
{
int paths[] = new int[100];
printPathsRecur(root, paths,0);
}
Node getNewNode(int val)
{
Node newNode = new Node();
newNode.data = val;
newNode.left = null;
newNode.right = null;
return newNode;
}
Node insert(Node root, int val)
{
if(root == null)
return getNewNode(val);
if(root.data < val)
root.right = insert(root.right, val);
else if(root.data > val)
root.left = insert(root.left,val);
return root;
}
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
Print_Tree_Paths obj = new Print_Tree_Paths();
Node root = null;
int n,val;
n = sc.nextInt();
while(n-- > 0)
{
val = sc.nextInt();
root = obj.insert(root, val);
}
obj.printPaths(root);
}
}