com.venky.tree.Node Maven / Gradle / Ivy
package com.venky.tree;
import java.util.ArrayList;
import java.util.List;
public class Node {
public Node(M data){
this.data = data;
this.parent = null;
}
private M data;
private Node parent;
private List> children = new ArrayList>();
public List> getChildren(){
return children;
}
public Node find(M data){
if (data.equals(data)){
return this;
}
for (Node child:getChildren()){
Node found = child.find(data);
if (found != null){
return found;
}
}
return null;
}
public Node add(M childChildData){
Node child = new Node(childChildData);
return add(child);
}
public Node add(Node child){
child.parent = this;
children.add(child);
return child;
}
public Node getParent(){
return parent;
}
public boolean isRoot(){
return parent == null;
}
public boolean isLeaf(){
return children.isEmpty();
}
public M data(){
return this.data;
}
public List getLeaves(){
List leaves = new ArrayList();
loadLeaves(leaves);
return leaves;
}
private void loadLeaves(List leafData){
if (isLeaf()){
leafData.add(data());
}
for (Node child:getChildren()){
child.loadLeaves(leafData);
}
return ;
}
}