forked from ambujraj/hacktoberfest2018
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Generic-Tree.java
76 lines (67 loc) · 1.7 KB
/
Generic-Tree.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
68
69
70
71
72
73
74
75
76
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class GenericTree {
private class Node {
int data;
ArrayList<Node> children;
Node(int data) {
this.data = data;
children = new ArrayList<>();
}
}
private Node root;
private int size = 0;
GenericTree() {
Scanner s = new Scanner(System.in);
this.root = takeInput(s, null, 0);
}
private Node takeInput(Scanner s, Node parent, int ithchild) {
if (parent == null) {
System.out.println("Enter the data for root Node");
} else {
System.out.println("Enter the data for " + ithchild + " th child of " + parent.data);
}
int nodeData = s.nextInt();
Node node = new Node(nodeData);
this.size++;
System.out.println("Please enter the number of children for " + node.data);
int numChildren = s.nextInt();
for (int i = 0; i < numChildren; i++) {
Node child = this.takeInput(s, node, i);
node.children.add(child);
}
return node;
}
public int height() {
return this.height(this.root);
}
private int height(Node node) {
int height = -1;
for (int i = 0; i < node.children.size(); i++) {
int heightofchild = this.height(node.children.get(i));
if (heightofchild > height) {
height = heightofchild;
}
}
height = height + 1;
return height;
}
}
public int size() {
return this.size;
}
public void display() {
this.display(this.root);
}
private void display(Node node) {
System.out.print(node.data + "=>");
for (int i = 0; i < node.children.size(); i++) {
System.out.print(node.children.get(i).data + ",");
}
System.out.println("END");
for (int i = 0; i < node.children.size(); i++) {
this.display(node.children.get(i));
}
}