递归方式实现二叉树的三种遍历

递归方式实现二叉树的先序、中序、后序遍历:

理解递归序:递归遍历的本质是递归序,二叉树递归序,每个节点都会达到三次。先序、中序、后序都可以在递归序的基础上加工出来,第一次到达一个节点就打印就是先序、第二次打印即中序、第三次即后序。

在这里插入图片描述

package com.harrison.class07;

public class Code01_RecursiveTraversalBT {
	public static class Node{
		public int value;
		public Node left;
		public Node right;
		
		public Node(int v) {
			value=v;
		}
	}
	
	public static void f(Node head) {
		if(head==null) {
			return ;
		}
		f(head.left);
		f(head.right);
	}
	
	public static void pre(Node head) {
		if(head==null) {
			return ;
		}
		System.out.print(head.value+" ");
		pre(head.left);
		pre(head.right);
	}
	
	public static void in(Node head) {
		if(head==null) {
			return ;
		}
		in(head.left);
		System.out.print(head.value+" ");
		in(head.right);
	}
	
	public static void pos(Node head) {
		if(head==null) {
			return ;
		}
		pos(head.left);
		pos(head.right);
		System.out.print(head.value+" ");
	}
	
	public static void main(String[] args) {
		Node head = new Node(1);
		head.left = new Node(2);
		head.right = new Node(3);
		head.left.left = new Node(4);
		head.left.right = new Node(5);
		head.right.left = new Node(6);
		head.right.right = new Node(7);

		pre(head);
		System.out.println("\n========");
		in(head);
		System.out.println("\n========");
		pos(head);
		System.out.println("\n========");

	}
}

  • 17
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 16
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱敲代码的Harrison

从来无所求,所得皆惊喜。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值