首页 > 解决方案 > 将订单代码转换为预购和后购

问题描述

我如何把它变成一个前序和后序遍历?此代码仅以中序样式遍历树。

void inorder() {
    inorderRec(root);
}

// Inorder Traversal
void inorderRec(Node root) {
    if (root != null) {
        inorderRec(root.left);
        System.out.print(root.key + " -> ");
        inorderRec(root.right);
    }
}

标签: javatree

解决方案


您可以更改语句的顺序:

void preOrderRec(Node root) {
    if (root != null) {
        System.out.print(root.key + " -> ");
        inorderRec(root.left);
        inorderRec(root.right);
     }

void postOrderRec(Node root) {
    if (root != null) {
        inorderRec(root.left);
        inorderRec(root.right);
        System.out.print(root.key + " -> ");
     }

推荐阅读