-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReplyNode.java
More file actions
99 lines (84 loc) · 2.31 KB
/
ReplyNode.java
File metadata and controls
99 lines (84 loc) · 2.31 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
package Test;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
/**
*
* @author asraf
*/
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/*Implement Tree data structure to create a hiearchy of post
*/
public class ReplyNode<T> implements Iterable<ReplyNode<T>> {
public T data;
public ReplyNode<T> parent;
public List<ReplyNode<T>> children;
/**
* Returns true if the node is a root.
* @return true, if this node is a root
*/
public boolean isRoot() {
return parent == null;
}
/**
* Returns true if the node is a leaf.
* @return true, if this node is a leaf.
*/
public boolean isLeaf() {
return children.size() == 0;
}
private List<ReplyNode<T>> elementsIndex;
public ReplyNode(T data) {
this.data = data;
this.children = new LinkedList<ReplyNode<T>>();
this.elementsIndex = new LinkedList<ReplyNode<T>>();
this.elementsIndex.add(this);
}
/**
* Adds a child node to a parent node.
* @param child Generic type
* @return the child node
*/
public ReplyNode<T> addChild(T child) {
ReplyNode<T> childNode = new ReplyNode<>(child);
childNode.parent = this;
this.children.add(childNode);
this.registerChildForSearch(childNode);
return childNode;
}
/**
* Returns the level of the node resides in.
* @return int value of the level the node is in
*/
public int getLevel() {
if (this.isRoot())
return 0;
else
return parent.getLevel() + 1;
}
private void registerChildForSearch(ReplyNode<T> node) {
elementsIndex.add(node);
if (parent != null)
parent.registerChildForSearch(node);
}
public ReplyNode<T> findTreeNode(Comparable<T> cmp) {
for (ReplyNode<T> element : this.elementsIndex) {
T elData = element.data;
if (cmp.compareTo(elData) == 0)
return element;
}
return null;
}
@Override
public String toString() {
return data != null ? data.toString() : "[data null]";
}
@Override
public Iterator<ReplyNode<T>> iterator() {
ReplyNodeIter<T> iter = new ReplyNodeIter<>(this);
return iter;
}
}