二叉树的遍历-递归方式

概述:用递归方式实现二叉树的遍历。


二叉树结构

public class Node{
        public int value;
        public Node left;
        public Node right;

        public Node(int data){
            this.value = data;
        }
}


先序遍历:先遍历根结点,再遍历左子树,最后遍历右子树

public void preOrderRecur(Node head){

        if(head == null){
            return;
        }

        System.out.print(head.value + " ");//先遍历根节点
        preOrderRecur(head.left);//遍历左子树
        preOrderRecur(head.right);//遍历右子树
}


中序遍历:先遍历左子树,再遍历根节点,最后遍历右子树

public void inOrderRecur(Node head){
        if(head == null){
            return;
        }

        inOrderRecur(head.left);//遍历左子树
        System.out.print(head.value + " ");//遍历根节点
        inOrderRecur(head.right);//遍历右结点
}


后序遍历:先遍历左子树,再遍历右子树,最后遍历根结点

public void posOrderRecur(Node head){
        if(head == null){
            return;
        }

        posOrderRecur(head.left);//遍历左子树
        posOrderRecur(head.right);//遍历右子树
        System.out.print(head.value + " ");//遍历根节点
}


测试函数:

public static void main(String[] args) {

        PrintTree pt = new PrintTree();

        /*

              建树
               1
            /     \
           2       3
         /   \    /  \
        4     5  6    7

       */
        Node root = new Node(1);//创建根结点
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);

        System.out.print("先序遍历:");
        pt.preOrderRecur(root);
        System.out.println();

        System.out.print("中序遍历:");
        pt.inOrderRecur(root);
        System.out.println();

        System.out.print("后序遍历:");
        pt.posOrderRecur(root);
        System.out.println();

}


运行结果:



猜你喜欢

转载自blog.csdn.net/hoji_James/article/details/80601375