二叉樹遍歷算法

二叉樹是一種非線性的數據結構,在對它進行操作時,總是需要逐一對每個數據元素實施操作,這樣就存在一個操作順序問題,由此提出了二叉樹的遍歷操作。所謂遍歷二叉樹就是按某種順序訪問二叉樹中的每個結點一次且僅一次的過程。這裏的訪問可以是輸出、比較、更新、查看元素內容等等各種操作。

在這裏寫了個二叉樹遍歷算法、根據三種不同的順序得到三種不同的順序結果、

public class BinaryTree {
	
	int data;
	BinaryTree left = null;
	BinaryTree right = null;
	
	public BinaryTree(int data){
		this.data = data;
	}
	
	
	public void insert(BinaryTree root,int data){//二叉樹中插入子結點
		
		if(data<root.data){//二叉樹左結點比根結點小
			
			if(root.left!=null){
				insert(root.left, data);
			}else{
				root.left = new BinaryTree(data);
			}
		}else{//二叉樹右結點比根結點大
			if(root.right!=null){
				insert(root.right, data);
			}else{
				root.right = new BinaryTree(data);
			}
			
		}
	}
	
	/**
	 * 
	 * @param root
	 * @param order 遍歷順序
	 * 1 先序	(根結點——>左結點——>右結點)
	 * 2 中序	(左結點——>根結點——>右結點)
	 * 3 後序	(左結點——>右結點——>根結點)
	 */
	public static void order(BinaryTree root ,int order){
		
		switch (order) {
		case 1://先序 
			
			if(root!=null){
				System.out.print(root.data+" --> ");
				order(root.left,order);
				order(root.right,order);
			}
			
			break;
		case 2://中序
			
			if(root!=null){
				order(root.left,order);
				System.out.print(root.data+" --> ");
				order(root.right,order);
			}
			
			break;
		case 3://後序
			
			if(root!=null){
				order(root.left,order);
				order(root.right,order);
				System.out.print(root.data+" --> ");
			}
			
			break;

		default:
			break;
		}
	}
	
	
	public static void main(String[] args) {
		
		int[] ints = {1,22,3,44,5,66,7,88,9,11};
		  BinaryTree root = new BinaryTree(ints[0]);   //創建二叉樹
		  for(int i=1;i<ints.length;i++){
		   root.insert(root, ints[i]);       //向二叉樹中插入數據
		  }
		  System.out.println("\n先序遍歷:");
		  order(root, 1);
		  System.out.println("\n中序遍歷:");
		  order(root, 2);
		  System.out.println("\n後序遍歷:");
		  order(root, 3);
	}

}


打印結果如下:


先序遍歷:
1 --> 22 --> 3 --> 5 --> 7 --> 9 --> 11 --> 44 --> 66 --> 88 --> 
中序遍歷:
1 --> 3 --> 5 --> 7 --> 9 --> 11 --> 22 --> 44 --> 66 --> 88 --> 
後序遍歷:
11 --> 9 --> 7 --> 5 --> 3 --> 88 --> 66 --> 44 --> 22 --> 1 -->


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章