使用java实现二叉树的三叉链表存储

        二叉链表和三叉链表实现二叉树的存储不同之处在于,三叉链表中的每一个结点多了一个指向父节点的区域,其他的地方和二叉链表没有什么区别,实现的思路和二叉链表一致,这里就不再赘述了,详情可以看上一篇二叉链表实现二叉树存储。直接上代码,不多BB。

                            二叉树三叉链表存储的java实现

java代码如下:

public class ThreeLinkBinTree<T> {
	/*
	 * 使用三叉链表实现二叉树的存储
	 * 使用一个内部类表示结点,结点有四个域,一个存放数据,一个指向父节点,一个指向左孩子结点,一个指向右孩子结点
	 * */
	public static class Node{
		private Object data;
		private Node parent;
		private Node left;
		private Node right;
		
		public Node(){
			
		}
		public Node(Object data){
			this.data=data;
		}
		public Node(Object data,Node parent,Node left,Node right){
			this.data=data;
			this.parent=parent;
			this.left=left;
			this.right=right;
		}
	}
	
	//保存二叉树的根节点
	private Node root;
	
	//提供两个构造函数用来构造二叉树
	public ThreeLinkBinTree(){
		root=new Node();
	}
	public ThreeLinkBinTree(T data){
		root=new Node(data);
	}
	
	//如果是使用无参的构造函数构造二叉树,则可以调用该方法给root结点的data赋值
	public void setRootData(T data){
		if(root.data==null){
			root.data=data;
		}else{
			throw new RuntimeException("root结点已经有数据,请不要重复设置");
		}
	}
	
	//根据指定结点添加子结点,parent为指定结点,data为数据,isLeft表示是否为左孩子节点
	public Node add(Node parent,T data,boolean isLeft){
		//如果parent为空或者parent的data为空都表示该父节点为空
		if(parent==null||parent.data==null){
			throw new RuntimeException("该父节点为空,不能添加子节点");
		}
		Node node=null;
		if(isLeft){
			if(parent.left!=null){
				throw new RuntimeException("该节点的左孩子节点不为空");
			}else{
				node = new Node(data);
				parent.left = node;				
			}			
		}else{
			if(parent.right!=null){
				throw new RuntimeException("该节点的右孩子结点不为空");
			}else{
				node = new Node(data);
				parent.right=node;				
			}
		}
		node.parent=parent;
		return node;
	}
	
	//判断二叉树是否为空
	public boolean isEmpty(){
		return root.data==null;
	}
	
	//获取根节点
	public Node getRoot(){
		if(isEmpty()){
			throw new RuntimeException("该二叉树为空,不能获取根节点");
		}
		return root;
	}
	
	//获取指定结点的父节点
	public Node getParent(Node node){
		if(node==null){
			throw new RuntimeException("该节点为空,不能获取父节点");
		}
		if(root==node){
			throw new RuntimeException("根节点没有父节点");
		}
		return node.parent;
	}
	
	//获取指定结点的左孩子节点
	public Node getLeft(Node node){
		if(node==null){
			throw new RuntimeException("该节点为空,不能获取左孩子节点");
		}
		return node.left;
	}
	
	//获取指定节点的右孩子节点
	public Node getRight(Node node){
		if(node==null){
			throw new RuntimeException("该节点为空,不能获取右孩子节点");
		}
		return node.right;
	}
	
	//获取二叉树的深度
	public int Deep(){
		return getDeep(root);
	}
	
	private int getDeep(Node node){
		if(node==null){//表示
			return 0;
		}
		if(node.left==null&&node.right==null){//这一步说明该节点没有左右孩子,但是节点不为空,深度+1
			return 1;
		}else{//如果节点的左右孩子有一个或者一个以上不为空,则递归算出该节点的左孩子深度和右孩子深度
			int leftDeep=getDeep(node.left);
			int rightDeep=getDeep(node.right);
			//父节点的最终深度为左孩子深度和右孩子深度的最大值+1
			int max=leftDeep>rightDeep?leftDeep:rightDeep;
			return max+1;
		}
	}
}

接下来应该是二叉树的遍历了,加油! 

猜你喜欢

转载自blog.csdn.net/qq_41300571/article/details/83008299