zoukankan      html  css  js  c++  java
  • 二叉树的遍历

    二叉树的先序遍历顺序为:父亲->左儿子->右儿子

    中序遍历顺序为:左儿子->父亲->右儿子

    后序遍历顺序为:右儿子->左儿子->父亲

    struct Node {
        int value;
        Node *left_child;
        Node *right_child;
        Node () {
            left_child = right_child = NULL;
        }
    };
    bool first = true;
    void Pre_order(Node *tree) {
        if(first) {
            cout << tree->value;
            first = false;
        } else cout << " " << tree->value;
    
        if(tree->left_child != NULL) {
            Pre_order(tree->left_child);
        }
        if(tree->right_child != NULL) {
            Pre_order(tree->right_child);
        }
    }
    void Mid_order(Node *tree) {
        if(tree->left_child != NULL) {
            Mid_order(tree->left_child);
        }
        if(first) {
            cout << tree->value;
            first = false;
        } else cout << " " << tree->value;
        if(tree->right_child != NULL) {
            Mid_order(tree->right_child);
        }
    }
    void Pos_order(Node *tree) {
        if(tree->left_child != NULL) {
            Pos_order(tree->left_child);
        }
        if(tree->right_child != NULL) {
            Pos_order(tree->right_child);
        }
        if(first) {
            cout << tree->value;
            first = false;
        } else cout << " " << tree->value;
    }
  • 相关阅读:
    2020/5/8
    2020/5/8
    2020/5/6
    2020/4/30
    2020/4/29
    2020/4/28
    2020/4/27
    KMP算法详解
    博客搬家声明
    洛谷P2831 NOIP2016 愤怒的小鸟
  • 原文地址:https://www.cnblogs.com/cshg/p/6576728.html
Copyright © 2011-2022 走看看