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

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

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

在这里插入图片描述

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========");

	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44337241/article/details/121815592