今天在做一个计算BOM成本的功能,BOM是一个由物料组成的树,规则是如果一个节点有子节点,那么这个节点的成本就是所有子节点之和,做这个功能最直接的想法就是通过递归的方式实现,后面查看到DefaultMutableTreeNode类有个实例方法depthFirstEnumeration(),查询API知道这个方法返回一个枚举,该枚举是已深度优先的顺序遍历此节点为根的子树,于是想自己写个深度遍历的实现,不过代码逻辑还理解不到位,暂时想不出,后续再补上代码。package com.jaws.tree;import java.util.ArrayList;import java.util.Iterator;import java.util.LinkedList;public class TreeNode {private TreeNode parent = null;//父节点private LinkedList children = null;//子节点链表private Object userObject = null;private int depth = 0;{children = new LinkedList();}public TreeNode(){}public TreeNode(Object userObject) {// TODO Auto-generated constructor stubthis.userObject = userObject;}public void add(TreeNode newChild){children.add(newChild);//添加到子节点链表中newChild.setParent(this);//设置子节点的父节点}public TreeNode getChildAt(int childIndex){if (childIndex<0 childindex="">this.children.size()-1) {return null;}else{return children.get(childIndex);}}public int getChildCount(){return children.size();}public TreeNode getParent() {return parent;}void setParent(TreeNode parent) {this.parent = parent;this.depth = parent.getDepth()+1;//设置本节点的深度}public Object getUserObject() {return userObject;}public void setUserObject(Object userObject) {this.userObject = userObject;}public int getDepth() {return depth;}public boolean isRoot(){if (parent==null) {return true;}else{return false;}}public boolean isLeaf(){if (children == null) { return true; } else { if (children.isEmpty()) { return true; } else { return false; } }}/** * 返回子节点链表的迭代器 * @return */public Iterator children(){return this.children.iterator();}public java.util.List getChildren(){return this.getChildren();}@Overridepublic String toString() {// TODO Auto-generated method stubreturn userObject!=null ? userObject.toString() : "";}}
JAVA树节点怎么标记_简易的Java树节点
最新推荐文章于 2022-09-07 16:18:11 发布