二叉树的遍历和先序创建(Java实现)

private static Node root;


    public static void main(String[] args) {
        root = createTree(root);
        preOrderPrint(root);
        System.out.println();
        inOrderPrint(root);
        System.out.println();
        postOrderPrint(root);
    }

    //先序构造树
    static Node createTree(Node add) {
        String str = readDataFromConsole("Please input char:");
        if (!str.equals(" ")) {
            add = new Node();
            add.elem = str;
            add.left = createTree(add.left);
            add.right = createTree(add.right);
        }
        //返回没有任何元素的节点
        return add;
    }

    static String readDataFromConsole(String prompt) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = null;
        try {
            System.out.print(prompt);
            str = br.readLine();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 先序遍历
     *
     * @param root
     */
    static void preOrderPrint(Node root) {
        if (root != null) {
            System.out.print(root.elem + "\t");
            preOrderPrint(root.left);
            preOrderPrint(root.right);
        } else {
            System.out.print("$" + "\t");
        }

    }

    /**
     * 中序遍历
     *
     * @param node
     */
    static void inOrderPrint(Node node) {
        if (node != null) {
            //遍历左子树
            inOrderPrint(node.left);
            //输出节点
            System.out.print(node.elem + "\t");
            //遍历右子树
            inOrderPrint(node.right);
        } else {
            System.out.print('$' + "\t");
        }
    }

    /**
     * 后序遍历
     *
     * @param node 节点
     */
    static void postOrderPrint(Node node) {
        if (node != null) {
            inOrderPrint(node.left);
            inOrderPrint(node.right);
            System.out.print(node.elem + "\t");
        } else {
            System.out.print('$' + "\t");
        }
    }

    static class Node {
        String elem;
        Node left;
        Node right;
    }

你可能感兴趣的:(二叉树的遍历和先序创建(Java实现))