首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将inorder代码转换为preorder和postorder

将inorder代码转换为preorder和postorder
EN

Stack Overflow用户
提问于 2021-01-13 21:05:02
回答 2查看 45关注 0票数 0

如何将其转换为预订单遍历和后订单遍历?此代码仅以inorder样式遍历树。

代码语言:javascript
复制
void inorder() {
    inorderRec(root);
}

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

回答 2

Stack Overflow用户

发布于 2021-01-13 21:11:17

您可以只更改语句的顺序:

代码语言:javascript
复制
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 + " -> ");
     }
票数 1
EN

Stack Overflow用户

发布于 2021-01-13 21:17:58

代码语言:javascript
复制
void preOrder(Node root)
{
if (root) {
System.out.print(root.key + " -> ");
preOrder(root.left);
preOrder(root.right);
}
}

void postOrder(Node root)
{
if (root) 
{
postOrder(root.left);
postOrder(root.right);
System.out.print(root.key + " -> ");
}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65702560

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档