java链表模型_基于 链表法 父亲长子兄弟模型树的实现 -java

本文介绍了如何使用Java实现基于链表的父亲长子兄弟模型的树结构,包括树的ADT接口定义和具体实现。通过树的深度、高度、获取父节点、子节点等方法展示了树的基本操作。
摘要由CSDN通过智能技术生成

关于树的性质,不用多说了。

利用父亲长子兄弟模型 用java来实现了树的结构及基本操作

直接上代码:

树的ADT:

package Tree;

/**

*树的ADT

*父亲 长子 弟弟 模型

* @author coffee

*

*/

public interface Tree {

//得到当前节点的对象

public Object getElement();

//设置当前节点的对象

public Object setElement(Object Element);

//得到当前节点的深度

public int getDepth();

//得到当前节点的高度

public int getHeight();

//返回父节点

public TreeLinkedListNode getParent();

//得到第一个孩子

public TreeLinkedListNode getFirstChild();

//得到下一个兄弟

public TreeLinkedListNode getNextSubling();

//得到当前节点为根的树的规模

public int getSize();

}

树的实现:

package Tree;

/**

* 链表法 父亲长子兄弟模型

* @author coffee

*/

public class TreeLinkedListNode implements Tree{

private Object element;//元素

private TreeLinkedListNode parent; //父亲

private TreeLinkedListNode firstChild;//第一个孩子

private TreeLinkedListNode nextSibling;//下一个兄弟;

public TreeLinkedListNode(Object Element,TreeLinkedListNode parent,TreeLinkedListNode firshChild,TreeLinkedListNode nextSibling){

this.element=Element;

this.parent=parent;

this.firstChild=firshChild;

this.nextSibling=nextSibling;

}

public TreeLinkedListNode (){

this(null,null,null,null);

}

/**

* 返回当前节点的深度 深度是根到此节点的路径长度

* depth(v)=depth(u)+1;

*时间复杂度为On;

*/

@Override

public int getDepth() {

int depth=0;//跟节点的深度为0;初始化为0

TreeLinkedListNode p = parent;

while(p!=null){

depth++;

p = p.getParent(); //指向上一个父亲 直到父节点为null 到根节点 由于是尾递归,所以写成了遍历的形式

}

return depth;

}

/**

* 用计算子节点的个数同样算出当前节点的高度

* height(v)>=height(u)+1; 如果 u为v的孩子节点

* height(v)=1+max(height(u)) u为所有孩子

* 父亲孩子兄弟模型递归方法

* @return

*/

@Override

public int getHeight() {

int height= -1; //叶子节点高度为0 所以初始值为-1

TreeLinkedListNode subtree = firstChild;//从第一个孩子开始

while(subtree!=null){

height=Math.max(height,subtree.getHeight()); //返回在孩子中取得最大的高度 依次比较 nextSibling的高度和第一个孩子的高度

subtree=subtree.nextSibling;

}

return height+1;

}

@Override

public TreeLinkedListNode getNextSubling() {

return null;

}

/*

*递归的算出当前节点所有子节点个数

*如果不计算递归 算法可以在N的时间复杂度算出size的大小

*父亲长子兄弟模型递归方法

*/

@Override

public int getSize() {

int size=1;//当前及节点也是本节点的子节点 叶子节点的size就是1 ,所以初始值为1

TreeLinkedListNode subtree=firstChild; //从第一个节点开始

while(subtree!=null){

size+=subtree.getSize();

subtree=subtree.nextSibling; //一定是子节点的兄弟节点

}

return size;

}

//返回当前元素 设置新的元素

@Override

public Object setElement(Object Element) {

Object temp= element;

element=Element;

return temp;

}

@Override

public Object getElement() {

return element;

}

public TreeLinkedListNode getParent() {

return parent;

}

public TreeLinkedListNode getFirstChild() {

return firstChild;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值