14、二叉树的先序,中序,后序遍历

这篇博客介绍了为什么需要树存储结构,对比了数组和链表的优缺点,并详细讲解了二叉树的三种遍历方式——前序遍历、中序遍历和后序遍历,以及它们的具体实现步骤。
摘要由CSDN通过智能技术生成

一、为什么需要树存储结构

  1. 数组存储方式的分析
    优点:通过下边访问数组元素,访问速度快。对于有序数组,可以使用二分查找、插值查找等方法提高检索速度。
    缺点:如果要删除或者在指定位置插入某个值,会造成大量元素移动,效率较低。
    在这里插入图片描述
  2. 单链表存储方式分析
    优点:在元素的插入、删除方面相对于数组方式有优化,效率得到提高。
    缺点:在进行检索时,需要链表头部依次检索,效率低。
    在这里插入图片描述

二、二叉树示意图

在这里插入图片描述

三、二叉树的遍历

  1. 前序遍历
    输出当前节点;若左子树不为空,递归遍历左子树;若右子树不为空,递归遍历右子树。

  2. 中序遍历
    若左子树不为空,递归遍历左子树;输出当前节点;若右子树不为空,递归遍历右子树。

  3. 后序遍历
    若左子树不为空,递归遍历左子树;若右子树不为空,递归遍历右子树;输出当前节点。

四、代码

package com.tree;

public class BinaryTreeTest {
	public static void main(String[] args) {
		TreeNode root = new TreeNode(1, "宋江");
		TreeNode node1 = new TreeNode(2, "张飞");
		TreeNode node2 = new TreeNode(3, "武松");
		TreeNode node3 = new TreeNode(4, "卢俊义");
		root.left = node1;
		root.right = node2;
		node2.right = node3;
		BinaryTree binaryTree = new BinaryTree(root);
		binaryTree.postOrder();
	}
}

class BinaryTree {
	public TreeNode root;

	public BinaryTree(TreeNode root) {
		this.root = root;
	}

	/**
	 * 前序遍历
	 */
	public void preOrder() {
		if (root != null) {
			root.preOrder();
		} else {
			System.out.println("树为空!");
		}
	}

	/**
	 * 中序遍历
	 */
	public void infixOrder() {
		if (root != null) {
			root.infixOrder();
		} else {
			System.out.println("树为空!");
		}
	}
	
	/**
	 * 后序遍历
	 */
	public void postOrder() {
		if (root != null) {
			root.postOrder();
		} else {
			System.out.println("树为空!");
		}
	}

}

class TreeNode {
	int id; // id
	String name; // 姓名
	TreeNode left; // 左子树
	TreeNode right; // 右子树

	public TreeNode(int id, String name) {
		this.id = id;
		this.name = name;
	}

	@Override
	public String toString() {
		return "TreeNode [id=" + id + ", name=" + name + "]";
	}

	/**
	 * 前序遍历
	 * 
	 * @param node
	 */
	public void preOrder() {
		// 先输出当前节点
		System.out.println(this);
		// 左子树不为空,遍历左子树
		if (this.left != null) {
			this.left.preOrder();
		}
		// 右子树不为空,遍历右子树
		if (this.right != null) {
			this.right.preOrder();
		}
	}

	/**
	 * 中序遍历
	 * 
	 * @param node
	 */
	public void infixOrder() {
		// 先遍历左子树
		if (this.left != null) {
			this.left.infixOrder();
		}
		// 输出当前节点
		System.out.println(this);
		// 遍历右子树
		if (this.right != null) {
			this.right.infixOrder();
		}
	}

	/**
	 * 后序遍历
	 * 
	 * @param node
	 */
	public void postOrder() {
		// 先遍历左子树
		if (this.left != null) {
			this.left.postOrder();
		}
		// 遍历左子树
		if (this.right != null) {
			this.right.postOrder();
		}
		// 输出当前节点
		System.out.println(this);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值