• 一个普通二叉树的遍历


    要点:二叉树遍历,要针对基本图形的遍历,先序(NLR),中序(LNR),后序(LRN),且往上看,它是某节点的左子,但往下看,它可能还是某节点的根,这时就要继续往下找,直到找到没有子(也就是叶子)时,左子,才是真正的左子,自己体会。

    图形:

    程序:

    #include<stdio.h>
    #include<stdlib.h>
    
    struct node{
        char data;
        struct node* left;
        struct node* right;
    };
    struct node* newNode(char 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("%c ",node->data);
    }
    void printInorder(struct node* node){
        if(node==NULL){
            return;
        }
        printInorder(node->left);
        printf("%c ",node->data);
        printInorder(node->right);
    }
    void printPreorder(struct node* node){
        if(node==NULL){
            return;
        }
        printf("%c ",node->data);
        printPreorder(node->left);
        printPreorder(node->right);
    }
    int main(){
        struct node *root=newNode('A');
        root->left=newNode('B');
        root->right=newNode('C');
        root->left->left=newNode('D');
        root->right->left=newNode('F');
        root->right->right=newNode('H');
        root->left->left->right=newNode('E');
        root->right->right->left=newNode('I');
        root->right->right->right=newNode('G');
        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
    A B D E C F H I G
    Inorder raversal of binary tree is
    D E B A F C I H G
    Postorder raversal of binary tree is
    E D B F G I H C A
  • 相关阅读:
    2020/2/14
    2020/2/13
    《人类简史》
    2020/2/12
    bzoj3157国王奇遇记(秦九韶算法+矩乘)&&bzoj233AC达成
    [noip科普]关于LIS和一类可以用树状数组优化的DP
    [uva11722&&cogs1488]和朋友会面Joining with Friend
    Bzoj2154 Crash的数字表格 乘法逆元+莫比乌斯反演(TLE)
    NOIP2016滚粗记
    bzoj2228[ZJOI2011]礼物(gift)
  • 原文地址:https://www.cnblogs.com/litifeng/p/10662009.html
Copyright © 2020-2023  润新知