zoukankan      html  css  js  c++  java
  • 二叉树建立和遍历

    闲着整理出来。

    #include <stdio.h>
    #include <string.h>
    #include <iostream>
    using namespace std;
    
    struct Node {
        int date;
        Node *lChild, *rChild;
    };
    
    int n;
    
    Node *create(int i) { // 建树
        Node *root;
        root = new Node();
        root->date = i;
        if (2*i <= n)
            root->lChild = create(2*i);
        else root->lChild = NULL;
    
        if (2*i+1 <= n)
            root->rChild = create(2*i+1);
        else root->rChild = NULL;
        return root;
    }
    
    void pre_order(Node *root) { // 先序遍历
        if (root == NULL)
            return;
        printf("%d ", root->date);
        pre_order(root->lChild);
        pre_order(root->rChild);
    }
    
    void in_order(Node *root) { // 中序遍历
        if (root == NULL)
            return;
        in_order(root->lChild);
        printf("%d ", root->date);
        in_order(root->rChild);
    }
    
    void post_order(Node *root) { // 后序遍历
        if (root == NULL)
            return;
        post_order(root->lChild);
        post_order(root->rChild);
        printf("%d ", root->date);
    }
    
    int main() {
        while(cin >> n) {
            Node *root = create(1);
    
            pre_order(root);
            cout << endl;
    
            in_order(root);
            cout << endl;
    
            post_order(root);
            cout << endl;
        }
        return 0;
    }
    

      

  • 相关阅读:
    10.19
    10.17
    张钊的作业
    张钊的第十一份作业
    张钊的第十份作业
    张昭的第九次作业
    张钊的第八份作业
    张钊的第七份作业
    张钊的第六次作业啊
    张钊O的第五次作业
  • 原文地址:https://www.cnblogs.com/icode-girl/p/5288907.html
Copyright © 2011-2022 走看看