package TreeNodeDemo.test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* 这里描述了一个节点
*
* @author hejianlin
* @Version 2018年11月2日
*/
public class TreeNode {
private int parentId;// 父亲id
private int selfId;// 个人id
protected String nodeName;// 节点名称
protected TreeNode parentNode;// 父节点对象
protected List<TreeNode> childList;// 子节点列表
// 声明带参数的构造器
public TreeNode(int parentId, int selfId, String nodeName) {
this.parentId = parentId;
this.selfId = selfId;
this.nodeName = nodeName;
}
/**
* 初始化子节点数组
*/
public void initChildList() {
if (null == childList) {
childList = new ArrayList<TreeNode>();
}
}
// 增加子节点方法
public void addChildNode(TreeNode treeNode) {
initChildList();
childList.add(treeNode);
}
/**
* 插入节点,可以将节点填加在本节点的子节点list中,或者递归添加在子节点的子节点list中
* @param treeNode
* @return
*/
public boolean insertJuniorNode(TreeNode treeNode) {
int parentId=treeNode.getParentId();
if(this.selfId==parentId) {
addChildNode(treeNode);
return true;
}else {
if(childList==null || childList.isEmpty()) {//说明本节点之前就没有子节点,而自己的id又与要插入的节点的父id匹配不上,所以不用递归下去
return false;
}
for(TreeNode node:childList) {
boolean f=node.insertJuniorNode(treeNode);//递归插入
if(f) {
return true;
}
}
}
return false;
}
//深度优先遍历
public void depthTraverse() {
System.out.println(nodeName);
if(null==childList||childList.isEmpty()) {
return;
}
for(TreeNode node:childList) {
node.depthTraverse();
}
}
//广度优先遍历
public void breadthTraverse() {
//使用队列暂存节点
LinkedList<TreeNode>linkedList=new LinkedList<TreeNode>();
linkedList.add(this);
while(!linkedList.isEmpty()) {
TreeNode node=linkedList.pop();//弹出第一个
System.out.println(node.getNodeName());
if(node.getChildList()==null || node.getChildList().isEmpty()) {
continue;
}
for(TreeNode treeNode:node.getChildList()) {
linkedList.add(treeNode);
}
}
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public int getSelfId() {
return selfId;
}
public void setSelfId(int selfId) {
this.selfId = selfId;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public TreeNode getParentNode() {
return parentNode;
}
public void setParentNode(TreeNode parentNode) {
this.parentNode = parentNode;
}
public List<TreeNode> getChildList() {
return childList;
}
public void setChildList(List<TreeNode> childList) {
this.childList = childList;
}
}