前序 中序 后序 遍历 递归 非递归算法 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()+",");
	}
}

 

 

    原文作者:递归算法
    原文地址: https://blog.csdn.net/tanyujing/article/details/9381451
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞