JAVA树节点怎么标记_简易的Java树节点

今天在做一个计算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() : "";}}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值