二叉树的递归遍历

本文详细介绍了二叉树的先序、中序和后序遍历算法,并通过代码实例展示了如何构建和遍历二叉树。涵盖了算法原理、代码实现以及输出结果分析。

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

先序遍历(先根遍历):首先访问根结点然后遍历左子树,最后遍历右子树。在遍历左、右子树时,仍然先访问根结点,然后遍历左子树,最后遍历右子树。

中序遍历:首先遍历左子树,然后访问根结点,最后遍历右子树。在遍历左、右子树时,仍然先遍历左子树,再访问根结点,最后遍历右子树。

后序遍历:后序遍历首先遍历左子树,然后遍历右子树,最后访问根结点,在遍历左、右子树时,仍然先遍历左子树,然后遍历右子树,最后遍历根结点。

定义并构造二叉树如下:

public class BinaryTree {

	int root; // 根节点
	BinaryTree left; // 左子树
	BinaryTree right; // 右子树

	public BinaryTree(int root) {
		this.root = root;
		left = null;
		right = null;
	}

	//递归构造二叉树,左节点小于根节点,右节点大于根节点
	public void builTree(BinaryTree tree, int root) {
		if (root > tree.root) {
			if (tree.right == null) {
				tree.right = new BinaryTree(root);
			} else {
				this.builTree(tree.right, root);
			}
		} else {
			if (tree.left == null) {
				tree.left = new BinaryTree(root);
			} else {
				this.builTree(tree.left, root);
			}
		}
	}
}

实例化二叉树并遍历:

public class BinaryTreePreorder {

	public static void main(String[] str) {
		int[] array = { 5, 3, 2, 1, 4, 8, 7, 6, 10, 9 };
		BinaryTree tree = new BinaryTree(array[0]); // 创建二叉树,初始化根节点
		for (int i = 1; i < array.length; i++) {
			tree.builTree(tree, array[i]); // 构造二叉树
		}
		System.out.println("先根遍历:");
		preOrder(tree);
		System.out.println();
		
		System.out.println("中根遍历:");
		inOrder(tree);
		System.out.println();
		
		System.out.println("后根遍历:");
		postOrder(tree);
	}

	public static void preOrder(BinaryTree tree) { // 先序遍历
		if (tree != null) {
			System.out.print(tree.root + "-");
			preOrder(tree.left);
			preOrder(tree.right);
		}
	}

	public static void inOrder(BinaryTree tree) { // 中序遍历

		if (tree != null) {
			inOrder(tree.left);
			System.out.print(tree.root + "-");
			inOrder(tree.right);
		}
	}

	public static void postOrder(BinaryTree tree) { // 后序遍历

		if (tree != null) {
			postOrder(tree.left);
			postOrder(tree.right);
			System.out.print(tree.root + "-");
		}
	}
}
二叉树的结构如下:


输出结果如下:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值