二叉树的先序、中序、后序遍历

复习一波,go!
三种遍历方式本质区别在于遍历顺序不同。
以L、D、R分别表示遍历左子树、访问根节点、访问右子树,先序遍历为DLR;中序遍历为LDR;后序遍历为LRD。(别只给三个字母就不认识谁是谁了,L就是left,……很好记忆)
有了遍历顺序,基于二叉树的递归定义,可得下述遍历二叉树的递归算法:

  1. 先序遍历二叉树的操作定义为:
    (1)访问根节点;
    (2)先序遍历左子树;
    (3)先序遍历右子树;
  2. 中序:
    (1)中序遍历左子树;
    (2)访问根节点;
    (3)中序遍历右子树;
  3. 后序:
    (1)后序遍历左子树;
    (2)后序遍历右子树;
    (3)访问根节点;

测试用的二叉树:

二叉树的先序、中序、后序遍历_第1张图片

递归代码:

public class ThreeOrders {
    public static void main(String[] args) {
        // 构造二叉树的代码,忽略,看图就好
        TreeNode n = new TreeNode("A"), l = new TreeNode("B"), r = new TreeNode(
                "C");
        n.left = l;
        n.right = r;
        l.left = new TreeNode("D");
        l.right = new TreeNode("E");
        r.left = new TreeNode("F");
        // 遍历
        System.out.print("先序遍历:");
        preOrder(n);
        System.out.print("\n中序遍历:");
        midOrder(n);
        System.out.print("\n后序遍历:");
        lastOrder(n);
    }

    private static void preOrder(TreeNode tree) {
        // 顺序DLR
        /*
         * visit(tree); if (tree.left != null) preOrder(tree.left); if
         * (tree.right != null) preOrder(tree.right);
         */
        // 写法2
        if (tree != null) {
            visit(tree);
            preOrder(tree.left);
            preOrder(tree.right);
        }
    }

    private static void midOrder(TreeNode tree) {
        if (tree != null) {
            midOrder(tree.left);
            visit(tree);
            midOrder(tree.right);
        }
    }

    private static void lastOrder(TreeNode tree) {
        if (tree != null) {
            lastOrder(tree.left);
            lastOrder(tree.right);
            visit(tree);
        }
    }

    private static void visit(TreeNode n) {
        System.out.print(n.data);
    }
}

class TreeNode {
    String data;
    TreeNode left, right;

    public TreeNode(String s) {
        data = s;
    }
}

结果:

先序遍历:ABDECF
中序遍历:DBEAFC
后序遍历:DEBFCA

你可能感兴趣的:(二叉树,遍历,递归,数据结构,java)