-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneric.java
More file actions
117 lines (101 loc) · 2.81 KB
/
generic.java
File metadata and controls
117 lines (101 loc) · 2.81 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package lec22;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class generic {
private Node root;
// public class Node{
// int value;
// ArrayList<Node> children;
// public Node (int value){
// this.value = value;
// this.children = new ArrayList<Node>();
// }
// }
public void insert(Scanner s){
System.out.println("enter root value");
int n = s.nextInt();
this.root = new Node(n);
insert(root,s);
}
private void insert(Node node, Scanner s){
while(true){
System.out.println(" more node of "+ node.value);
boolean yes = s.nextBoolean();
if(yes){
System.out.println("Enter the value of child");
int value = s.nextInt();
Node child = new Node(value);
root.children.add(child);
insert(child,s);
}
else{
break;
}
}
}
public void display(){
display(root," ");
}
private void display(Node node,String indent){
System.out.println(indent+node.value);
for (int i = 0; i <node.children.size() ; i++) {
display(node.children.get(i),indent+"\t");
}
}
public int count(){
return count(root);
}
private int count(Node node){
int cnt = 1;
for (int i = 0; i <node.children.size() ; i++) {
cnt+= count(node.children.get(i));
}
return cnt;
}
public int max(){
int max = root.value;
return max(root,max);
}
private int max(Node node, int max){
if(max<node.value){
max=node.value;
}
for (int i = 0; i <node.children.size() ; i++) {
max = max(node.children.get(i),max);
}
return max;
}
public void levelorder(){
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
Node temp = queue.remove();
//printing temp.value here
// System.out.println(temp.value); // just for trial
for (int i = 0; i <temp.children.size() ; i++) {
queue.add(temp.children.get(i));
}
}
}
public void atlevel(int k){
atlevel(root,k);
}
public void atlevel(Node node, int k){
if(k==0){
System.out.println(node.value);
}
for (int i = 0; i <node.children.size() ; i++) {
atlevel(node.children.get(i),k-1);
}
}
public class Node{
int value;
ArrayList<Node> children;
public Node (int value){
this.value = value;
this.children = new ArrayList<Node>();
}
}
}