Java实现二叉树前中后序递归遍历以及非递归遍历

本文深入探讨了二叉树的遍历算法,包括前序、中序和后序遍历的非递归与递归实现。通过具体的代码示例,详细解释了每种遍历方式的原理和步骤,为理解二叉树数据结构提供了实用的指导。

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

package Main;

import java.util.Stack;

public class Test2 {

	public static void main(String[] args) {
		Tree root=new Tree(0);
		root.left=new Tree(1);
		root.right=new Tree(2);
		root.left.left=new Tree(3);
		root.left.right=new Tree(4);
		root.right.left=new Tree(5);
		root.right.right=new Tree(6);
		root.left.left.left=new Tree(7);
		root.right.right.right=new Tree(8);
		
		//前序遍历(非递归)  根左右
		System.out.println("前序遍历(非递归)");
		Stack<Tree> stack=new Stack<>();
		Tree t=root;
		stack.push(t);
		while(!stack.isEmpty()) {//思路:根据前序遍历(根左右)特点,优先遍历根节点,再而处理左右节点,通过循环就可以实现前序遍历
			t=stack.pop();
			System.out.print(t.val()+" ");
			if(t.right!=null) {
				stack.push(t.right);
			}
			if(t.left!=null) {
				stack.push(t.left);
			}
		}
		System.out.println("");
		//后序遍历(非递归)   左根右
		System.out.println("后序遍历(非递归)");
		Stack<Tree> stack2=new Stack<>();
		Stack<Tree> stack3=new Stack<>();
		Tree t2=root;
		stack2.push(t2);
		while(!stack2.isEmpty()) {//这里先根据Stack先进后出的特性,将二叉树通过后序遍历特点push进stack
			t2=stack2.pop();
			stack3.push(t2);
			if(t2.left!=null) {
				stack2.push(t2.left);
			}
			if(t2.right!=null) {
				stack2.push(t2.right);
			}
		}
		while(!stack3.isEmpty()) {//最后将stack出栈,就可以达到后序遍历二叉树
			System.out.print(stack3.pop().val()+" ");
		}
		System.out.println();
		//中序遍历(非递归) 左右根
		System.out.println("中序遍历(非递归)");
		Stack<Tree> stack4=new Stack<>();
		Tree t3=root;
		while(t3!=null||!stack4.isEmpty()) {//思路:根据中序遍历特点,优先找左节点
			if(t3!=null) {
				stack4.push(t3);
				t3=t3.left;
			}else {
				t3=stack4.pop();
				System.out.print(t3.val()+" ");
				t3=t3.right;
			}
		}
		System.out.println("\n前序遍历(递归)");
		pre(root);
		System.out.println("\n后序遍历(递归)");
		last(root);
		System.out.println("\n中序遍历(递归)");
		mid(root);
	}
	//前序遍历(递归)
	public static void pre(Tree root) {
		if(root!=null) {
			System.out.print(root.val()+" ");
			pre(root.left);
			pre(root.right);
		}
	}
	//中序遍历(递归)
	public static void mid(Tree root) {
		if(root!=null) {
			mid(root.left);
			System.out.print(root.val()+" ");
			mid(root.right);
		}
	}
	//后序遍历(递归)
	public static void last(Tree root) {
		if(root!=null) {
			last(root.left);
			last(root.right);
			System.out.print(root.val()+" ");
		}
	}
}
class Tree{
	private int val;
	public Tree left;
	public Tree right;
	public Tree(int val) {
		this.val=val;
	}
	public int val() {
		return this.val;
	}
}

二叉树形状

遍历输出结果

前序遍历(非递归)
0 1 3 7 4 2 5 6 8 
后序遍历(非递归)
7 3 4 1 5 8 6 2 0 
中序遍历(非递归)
7 3 1 4 0 5 2 6 8 
前序遍历(递归)
0 1 3 7 4 2 5 6 8 
后序遍历(递归)
7 3 4 1 5 8 6 2 0 
中序遍历(递归)
7 3 1 4 0 5 2 6 8 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值