前序 中序 後序 遍歷 遞歸 非遞歸算法 java實現

前序遍歷 非遞歸

 

	public void preordernorec(TreeNode root){
		//System.out.println("先序遍歷(非遞歸):");
		//用數組模擬棧,假設有節點個數不超過32個
		TreeNode[] stack = new TreeNode[32];
		for(int i =0;i<32;i++){
			stack[i] = null;
		}
		int index =0;
		TreeNode pnode = root;
		while(pnode!=null||index>0){
			while(pnode!=null){
				System.out.print(pnode.getKey()+",");
				stack[index++] = pnode;				
				pnode = pnode.getLeftchlid();
			}
			pnode = stack[--index];
			pnode = pnode.getRightchild();
		}
		//System.out.println("");
	}


 

前序遍歷 遞歸

public void preorder(TreeNode root){
		
		if(root!=null){
			System.out.print(root.getKey()+",");
			preorder(root.getLeftchlid());
			preorder(root.getRightchild());
		}
	}


 

中序遍歷 非遞歸

	public void inordernorec(TreeNode root){
		TreeNode[] stack = new TreeNode[32];
		int index=0;
		for(int i =0;i<32;i++){
			stack[i] = null;
		}
		TreeNode pnode = root;
		while(pnode!=null||index>0){
			while(pnode!=null){
				stack[index++] = pnode;
				pnode = pnode.getLeftchlid();
			}
			pnode = stack[--index];
			System.out.print(pnode.getKey()+",");
			pnode = pnode.getRightchild();
		}
		
		//System.out.println("");
	}


 

中序遍歷 遞歸

 

public void inorder(TreeNode root){
		
		if(root!=null){
			
			inorder(root.getLeftchlid());
			System.out.print(root.getKey()+",");
			inorder(root.getRightchild());
		}
	}


 

後序遍歷 非遞歸

 

public void postordernorec(TreeNode root){
	TreeNode[] stack = new TreeNode[32];
	int index=0;
	for(int i =0;i<32;i++){
		stack[i] = null;
	}
	TreeNode pnode = root;
	TreeNode LastVisit = null;
	while(pnode!=null||index>0){
		while(pnode!=null){
			stack[index++] = pnode;
			pnode = pnode.getLeftchlid();
		} 
		pnode=stack[index-1];
		if(pnode.getRightchild()==null||pnode.getRightchild()==LastVisit){
			System.out.print(pnode.getKey()+",");
			LastVisit = pnode;
			index--;
			pnode = null;
		}
		else
		{
			pnode = pnode.getRightchild();
		}
	}
}


 

後序遍歷 遞歸

public void postorder(TreeNode root){
	if(root!=null){
		postorder(root.getLeftchlid());
		postorder(root.getRightchild());
		System.out.print(root.getKey()+",");
	}
}


 

 

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