树根问题代码java 树的后根遍历代码( 二 )


* All Rights Reserved.
*
* 文件名称: ManyTreeNode.java
* 摘 要:
* 作 者: Walker
* 创建时间: 2013-03-19
*/
package com.walker.commons.data.model;
import java.util.ArrayList;
import java.util.List;
/**
* 多叉树节点
*
* @author Walker
* @verion 1.0.0.0
*/
public class ManyTreeNode
{
/** 树节点*/
private TreeNode data;
/** 子树集合*/
private ListManyTreeNode childList;
/**
* 构造函数
*
* @param data 树节点
*/
public ManyTreeNode(TreeNode data)
{
this.data = https://www.04ip.com/post/data;
this.childList = new ArrayListManyTreeNode();
}
/**
* 构造函数
*
* @param data 树节点
* @param childList 子树集合
*/
public ManyTreeNode(TreeNode data, ListManyTreeNode childList)
{
this.data = https://www.04ip.com/post/data;
this.childList = childList;
}
public TreeNode getData() {
return data;
}
public void setData(TreeNode data) {
this.data = https://www.04ip.com/post/data;
}
public ListManyTreeNode getChildList() {
return childList;
}
public void setChildList(ListManyTreeNode childList) {
this.childList = childList;
}
}
ManyNodeTree.java
/*
* Copyright Walker Studio
* All Rights Reserved.
*
* 文件名称: ManyNodeTree.java
* 摘 要:
* 作 者: Walker
* 创建时间: 2013-03-19
*/
package com.walker.commons.data.model;
import java.util.ArrayList;
import java.util.List;
/**
* 多叉树生成、遍历工具
*
* @author Walker
* @version 1.0.0.0
*/
public class ManyNodeTree
{
/** 树根*/
private ManyTreeNode root;
/**
* 构造函数
*/
public ManyNodeTree()
{
root = new ManyTreeNode(new TreeNode("root"));
}
/**
* 生成一颗多叉树,根节点为root
*
* @param treeNodes 生成多叉树的节点集合
* @return ManyNodeTree
*/
public ManyNodeTree createTree(ListTreeNode treeNodes)
{
if(treeNodes == null || treeNodes.size()0)
return null;
ManyNodeTree manyNodeTree =new ManyNodeTree();
//将所有节点添加到多叉树中
for(TreeNode treeNode : treeNodes)
{
if(treeNode.getParentId().equals("root"))
{
//向根添加一个节点
manyNodeTree.getRoot().getChildList().add(new ManyTreeNode(treeNode));
}
else
{
addChild(manyNodeTree.getRoot(), treeNode);
}
}
return manyNodeTree;
}
/**
* 向指定多叉树节点添加子节点
*
* @param manyTreeNode 多叉树节点
* @param child 节点
*/
public void addChild(ManyTreeNode manyTreeNode, TreeNode child)
{
for(ManyTreeNode item : manyTreeNode.getChildList())
{
if(item.getData().getNodeId().equals(child.getParentId()))
{
//找到对应的父亲
item.getChildList().add(new ManyTreeNode(child));
break;
}
else
{
if(item.getChildList() != nullitem.getChildList().size()0)
{
addChild(item, child);
}
}
}
}
/**
* 遍历多叉树
*
* @param manyTreeNode 多叉树节点
* @return
*/
public String iteratorTree(ManyTreeNode manyTreeNode)
{
StringBuilder buffer = new StringBuilder();
buffer.append("\n");
if(manyTreeNode != null)
{
for (ManyTreeNode index : manyTreeNode.getChildList())
{
buffer.append(index.getData().getNodeId()+ ",");
if (index.getChildList() != nullindex.getChildList().size()0 )

推荐阅读