-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree Input & Print Recursively.java
67 lines (50 loc) · 1.41 KB
/
Tree Input & Print Recursively.java
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
********************************Taking Tree Input from User and Printing it Recursively************************************************
import java.util.*;
class TreeNode<T>
{
T data;
ArrayList<TreeNode<T>>children;
public TreeNode(T data)
{
this.data=data;
children=new ArrayList();
}
}
public class Main
{
static TreeNode takeInput(Scanner sc)
{
System.out.println("Enter Root Data ");
int rootdata=sc.nextInt();
TreeNode<Integer>root=new TreeNode(rootdata);
System.out.println("Enter Root's Number of Children ");
int childrens=sc.nextInt();
for(int i=0;i<childrens;i++)
{
TreeNode rooter=takeInput(sc);
root.children.add(rooter);
}
return root;
}
static void print(TreeNode<Integer>root)
{
String s=root.data+":";
for(int i=0;i<root.children.size();i++)
{
if(i!=root.children.size()-1)
s+=root.children.get(i).data+",";
else
s+=root.children.get(i).data;
}
System.out.println(s);
for(int i=0;i<root.children.size();i++)
{
print(root.children.get(i));
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
TreeNode root=takeInput(sc);
print(root);
}
}