前序 中序 后序 遍历 递归 非递归算法 java实现

这篇博客详细介绍了二叉树的前序、中序和后序遍历的递归与非递归算法实现,包括前序遍历的非递归方法、前序遍历的递归方法、中序遍历的非递归和递归方法,以及后序遍历的非递归和递归策略,全部使用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()+",");
	}
}


 

 

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值