二叉树遍历——递归与非递归实现

描述

实现二叉树的先序、中序、后序遍历,包括递归方式和非递归方式。

分析

使用递归实现二叉树遍历十分容易。在递归过程中,系统自动帮你压栈从而回溯时,关键信息不会被丢失。而非递归实现二叉树遍历时,无法再依赖系统提供的栈。你只能自己去决定压栈出栈的策略来完成非递归版本的遍历。

递归版本的二叉树遍历

设计

在这里插入图片描述

使用递归时二叉树每个节点都会被遍历三次。
递归访问二叉树:

// 递归遍历
void vistNode(Node node) {
   
	if (node == null)
		return;
	visitNode(node);
	visitNode(node);
}

遍历顺序:
1 2 4 null 4 null 4 2 5 null 5 null 5 2 1 3 6 null 6 null 6 3 null 3 1
某个数第一次被遍历到时访问它,得到的序列就是先序遍历这颗二叉树的序列:1 2 4 5 3 6
某个数第二次被遍历到时访问它,得到的序列就是中序遍历这颗二叉树的序列:4 2 5 1 6 3
某个数第三次被遍历到时访问它,得到的序列就是后序遍历这颗二叉树的序列:4 5 2 6 3 1

代码
public class BinaryTreeTraversal {
   
	// 先序遍历
    public static void preorderRecursion(Node node) {
   
        if (node == null)
            return;
        System.out.print(node.element + " ");
        preorderRecursion(node.left);
        preorderRecursion(node.right);
    }
   	// 中序遍历
    public static void inorderRecursion(Node node) {
   
        if (node == null)
            return;
        inorderRecursion(node.left);
        System.out.print(node.element + " ");
        inorderRecursion(node.right);
    }
	// 后序遍历 
    public static void postorderRecursion(Node node) {
   
        if (node == null)
            return;
        postorderRecursion(node.left);
        postorderRecursion(node.right);
        System.out.print(node.element + " ");
    }
    
    public static void main(String[] args) {
   
        Node tree = new Node(1);	
        tree.left = new Node(2);
        tree.right = new Node(3);
        tree.left.left = new Node(4);
        tree.left.right = new Node(5);
        tree.right.left = new Node(6);
        System.out.print
  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值