package tree;
public class BinaryTreeNode {
private Object data; //数值域
private BinaryTreeNode parent;//父节点
private BinaryTreeNode lChild;
private BinaryTreeNode rChild;
private int height;//当前节点的高度
private int size;//当前节点的节点个数
//根据数据创造一个节点
public BinaryTreeNode(Object e){
data=e;
parent=null;
lChild=null;
rChild=null;
height=1;
size=1;
}
public BinaryTreeNode(){
this(null);
}
//判断是否有父节点
//++++++++++++++++++++++++++++判断是否有节点++++++++++++++
public boolean hasParent(){
return parent!=null;
}
public boolean hasLChild(){
return lChild!=null;
}
public boolean hasRChild(){
return rChild!=null;
}
//判断是否为也叶子节点
public boolean isLeaf(){
return rChild==null && lChild==null;
}
//判断是否为父节点的左孩子
public boolean isLChild(){
return parent!=null && parent.lChild==this;
}
//判断是否为父节点的有孩子
public boolean isRChild(){
return parent!=null && parent.rChild==this;
}
//+++++++++++++++++++++++++++与heught相关的操作++++++++++++++
//当接待你树的高度
public int getHeight(){
return height;
}
//更新当前节点的高度
public void updateHeight(){
int newHeight=0;
//当前节点的高度 左子树或者右子树 +1 就是当前节点的字数
if(hasLChild()){
newHeight= Math.max(newHeight, getLChild().getHeight()+1) ;
}
if(hasRChild()){
newHeight= Math.max(newHeight, getRChild().getHeight()+1) ;
}
if(height==newHeight){
return;
}
height=newHeight;
//祖先节点的高度
if(hasParent()){
getParent().updateHeight();
}
}
//当前节点的size个数++++++++++++++++++++++
//获取当前size;
public int getSize(){
return size;
}
//更新当前节点及父节点
public void updateSize(){
size=1;//当前节点
//累加左子树
if(hasLChild()){
size=size+getLChild().getSize();
}
//累加右子树
if(hasRChild()){
size+=getRChild().getSize();
}
//递归更新祖节点
if(hasParent()){
getParent().updateSize();
}
}
//与父结点相关的操作+++++++++++++++++++++++++++++++++++
//返回父节点
public BinaryTreeNode getParent(){
return parent;
}
//断开与父节点的关系
public void disNode(){
//没有父节点
if(!hasParent()){
return;
}
//有父节点
if(isLChild()){
parent.lChild=null;
}
if(isRChild()){
parent.rChild=null;
}
parent.updateHeight();//更新父节点的高度
parent.updateSize();
//当前节点的父节点为空
parent=null;
}
//返回左孩子相关的操作++++++++++++++++++++++++++++
public BinaryTreeNode getLChild(){
return lChild;
}
public BinaryTreeNode setLChild(BinaryTreeNode newLChild){
BinaryTreeNode oldLChild=this.lChild; //保存当前节点左孩子
//判断当前节点是否有左孩子
if(hasLChild()){
lChild.disNode(); //先断开当前节的左孩子
}
//设置左孩子为参数节点
if(newLChild!=null){
//如果新的节点还有父节点 就先断开父节点
newLChild.disNode(); //断开这个系欸但的父节点
this.lChild=newLChild;
newLChild.parent=this; //新节点的父节点为当前节点
this.updateHeight();
this.updateSize();
}
return oldLChild; //返回原来的左孩子
}
//返回右孩子相关的操作++++++++++++++++++++++++++++
public BinaryTreeNode getRChild(){
return rChild;
}
public BinaryTreeNode setRChild(BinaryTreeNode newRChild){
BinaryTreeNode oldRChild=this.rChild;//获取当前右节点
//判断是否有右的节点
if(hasRChild()){
rChild.disNode();
}
if(hasParent()){
newRChild.disNode();
this.rChild=newRChild;
newRChild.parent=this;
this.updateHeight();
this.updateSize();
}
return oldRChild;
}
}
定义二叉树的方法集 简单
最新推荐文章于 2022-09-01 20:09:24 发布