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

来源:互联网 发布:centos 7.0安装教程 编辑:程序博客网 时间:2024/06/08 06:29

先序遍历:中、左、右

中序遍历:左、中、右

后序遍历:左、右、中


比如下面这科树

             1

        2       3

    4    5   6    7

package com.sangfor.tree;public class Node {public int value;public Node left;public Node right;public Node(int value) {this.value = value;}}

package com.sangfor.tree;public class ForEachTree {    public static void main(String[] args) {    Node node1 = new Node(1);    Node node2 = new Node(2);    Node node3 = new Node(3);    Node node4 = new Node(4);    Node node5 = new Node(5);    Node node6 = new Node(6);    Node node7 = new Node(7);    node1.left = node2;    node1.right = node3;    node2.left = node4;    node2.right = node5;    node3.left = node6;    node3.right = node7;    System.out.println("前序列递归");    priOrder(node1);    System.out.println();    System.out.println("中序列递归");    inOrder(node1);    System.out.println();    System.out.println("后序列递归");    posOrder(node1);}    //前序列递归    public static void priOrder(Node head) {    if (head == null) {    return;    }    System.out.print(head.value+"\t");    priOrder(head.left);    priOrder(head.right);    }        //中序列递归    public static void inOrder(Node head) {    if (head == null) {    return;    }    inOrder(head.left);    System.out.print(head.value+"\t");    inOrder(head.right);    }        //后序列递归    public static void posOrder(Node head) {    if (head == null) {    return;    }    posOrder(head.left);    posOrder(head.right);    System.out.print(head.value+"\t");    }}

运行结果

前序列递归1245367中序列递归4251637后序列递归4526731


0 0
原创粉丝点击