• 二叉树遍历-c实现


    这里主要是三种遍历,先序(preorder,NLR),中序(Inorder,LNR),后序(Postorder,LRN)

    N:node,L:left,R:right

    基本排序:先序(NLR,节点,左,右),中序(LNR,左,节点,右),后序(LRN,左,右,节点)

    要点:在每一种排序里,必须遵守基本排序。看图:

    为了更加直观的了解,看下面的c语言实现的代码,参考了:https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/

    #include<cstdio>
    #include<cstdlib>
    using namespace std;
    struct node{
        int data;
        struct node* left;
        struct node* right;
    };
    struct node* newNode(int data){
        struct node* node = (struct node*)malloc(sizeof(struct node));
        node->data=data;
        node->left=NULL;
        node->right=NULL;
        return node;
    }
    void printPostorder(struct node* node){
        if(node == NULL)
            return;
        printPostorder(node->left);
        printPostorder(node->right);
        printf("%d ",node->data);
    }
    void printInorder(struct node* node){
        if(node==NULL){
            return;
        }
        printInorder(node->left);
        printf("%d ",node->data);
        printInorder(node->right);
    }
    void printPreorder(struct node* node){
        if(node==NULL){
            return;
        }
        printf("%d ",node->data);
        printPreorder(node->left);
        printPreorder(node->right);
    }
    int main(){
        struct node *root=newNode(1);
        root->left=newNode(2);
        root->right=newNode(3);
        root->left->left=newNode(4);
        root->left->right=newNode(5);
        root->right->left=newNode(6);
        root->right->right=newNode(7);
        root->left->left->left=newNode(8);
        root->left->left->right=newNode(9);
        root->left->right->left=newNode(10);
        root->left->right->right=newNode(11);
        root->right->left->left=newNode(12);
        root->right->left->right=newNode(13);
        root->right->right->left=newNode(14);
        root->right->right->right=newNode(15);
        printf("
    Preorder raversal of binary tree is 
    ");
        printPreorder(root);
        printf("
    Inorder raversal of binary tree is 
    ");
        printInorder(root);
        printf("
    Postorder raversal of binary tree is 
    ");
        printPostorder(root);
        return 0;
    }

    输出:

    Preorder raversal of binary tree is
    1 2 4 8 9 5 10 11 3 6 12 13 7 14 15
    Inorder raversal of binary tree is
    8 4 9 2 10 5 11 1 12 6 13 3 14 7 15
    Postorder raversal of binary tree is
    8 9 4 10 11 5 2 12 13 6 14 15 7 3 1

    写一个中序输出的图解:

  • 相关阅读:
    架构,改善程序复用性的设计(目录)
    如何让你的系统配置文件更合理
    MVC验证(自动在基类中验证实体的数据有效性),本人最满意的作品之一
    MVC验证(只验证指定字段)
    Redis学习笔记~实现消息队列比MSMQ更方便
    FRG图像文件格式(四):编码技术
    缓冲区
    Oracle体系结构及备份(十一)——bcakgroundprocess
    Excel编程(2)自动填充
    设计模式:策略模式
  • 原文地址:https://www.cnblogs.com/litifeng/p/10659895.html
Copyright © 2020-2023  润新知