1. 程式人生 > >使用java實現二叉樹的三叉連結串列儲存

使用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;
		}
	}
}

接下來應該是二叉樹的遍歷了,加油!