java算法(三)迭代(非递归)实现二叉树的前序中序后序遍历

本文介绍了一种不使用递归实现二叉树遍历的方法,包括前序、中序和后序遍历的具体步骤及代码实现。前序遍历通过一个栈来保存待处理节点;中序遍历则利用栈的特性实现左子树遍历后再访问根节点;后序遍历采用双栈法完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

递归无疑是遍历二叉树最简洁的方式,其依赖的是函数栈,非递归实现的话只要通过栈的辅助就可以了。


前序遍历:根节点首先入栈,然后栈中元素依次出栈,每次出栈时压入该元素的右孩子和左孩子(注意这个顺序,这样弹出时才是左孩子在前)

public void frontPrint(BTree tree){
		if (tree==null) {
			return;
		}
		Stack<BTree> stack=new Stack<>();
		stack.push(tree);
		BTree temp=tree;
		while(!stack.isEmpty()){
			BTree tr=stack.pop();
			System.out.print(tr.value+"  ");
			if (tr.right!=null) {
				stack.push(tr.right);
			}
			if (tr.left!=null) {
				stack.push(tr.left);
			}
		}
	}

中序遍历:依次遍历左孩子入栈,到头后弹出栈顶元素并开始处理右孩子。

public void centerPrint(BTree tree){
		if (tree==null) {
			return;
		}
		Stack<BTree> stack=new Stack<>();
		BTree temp=tree;
		while(!stack.isEmpty()||temp!=null){
			if (temp!=null) {
				stack.push(temp);
				temp=temp.left;
			} else {
				BTree bt=stack.pop();
				System.out.print(bt.value+"   ");
				temp=bt.right;
			}
		}
	}


后序遍历:要用到两个栈,根节点首先入栈1,然后栈1依次出栈,每次出栈时该元素入栈2并将左右孩子压入栈1。最后得到的栈2依次出栈就是后序遍历结果。

public void behindPrint(BTree tree){
		if (tree==null) {
			return;
		}
		Stack<BTree> stack1=new Stack<>();
		Stack<BTree> stack2=new Stack<>();
		stack1.push(tree);
		BTree temp=tree;
		while(!stack1.isEmpty()){
			BTree tr=stack1.pop();
			stack2.push(tr);
			if (tr.left!=null) {
				stack1.push(tr.left);
			}
			if (tr.right!=null) {
				stack1.push(tr.right);
			}
		}
		while (!stack2.isEmpty()) {
			System.out.print(stack2.pop().value+"  ");
		}
	}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值