zoukankan      html  css  js  c++  java
  • 二叉树的前中后序遍历简单的递归

    二叉树的遍历 无外乎广度和深度 其中深度又分为前中后序遍历三种情况  这三种遍历若只是递归方法 自然很是简单 但递归代码简单 若嵌套层次太深 会栈溢出

    二叉树节点数据结构:

    struct Binary_node
    {
        int val;
        Binary_node *left;
        Binary_node *right;
        Binary_node(int v = 0, Binary_node *le = nullptr, Binary_node *ri = nullptr) :val(v), left(le), right(ri)
        {}
    };
    

    二叉树类:

    class BinaryTree
    {
    public:
        struct Binary_node *root;
    
        BinaryTree(Binary_node *pnode = nullptr) : root(pnode){}
        ~BinaryTree(){}
    
        void pre_order_recur(Binary_node *root, std::vector<int> &res);
        void in_order_recur(Binary_node *root, std::vector<int> &res);
        void post_order_recur(Binary_node *root, std::vector<int> &res);
    
        std::vector<int> pre_order_iter(Binary_node *root);
        std::vector<int> in_order_iter(Binary_node *root);
        std::vector<int> post_order_iter(Binary_node *root);
    
        //广度遍历
        std::vector<int> level_trave(Binary_node *root);
    };
    

    前中后序遍历的递归方法  不多做说明 太简单:

    void BinaryTree::pre_order_recur(Binary_node *root, std::vector<int> &res)
    {
        if (root)
        {
            res.push_back(root->val);
            pre_order_recur(root->left, res);
            pre_order_recur(root->right, res);
        }
    }
    void BinaryTree::in_order_recur(Binary_node *root, std::vector<int> &res)
    {
        if (root)
        {
            in_order_recur(root->left, res);
            res.push_back(root->val);
            in_order_recur(root->right, res);
        }
    }
    void BinaryTree::post_order_recur(Binary_node *root, std::vector<int> &res)
    {
        if (root)
        {
            post_order_recur(root->left, res);
            post_order_recur(root->right, res);
            res.push_back(root->val);
        }
    }
    
  • 相关阅读:
    ☆ [HDU2157] How many ways?? 「矩阵乘法求路径方案数」
    [HDU2065] "红色病毒"问题
    [SP1043] GSS1
    [POJ3233] Matrix Power Series
    「网络流24题」圆桌问题
    [BZOJ4260] Codechef REBXOR
    [HDU5536] Chip Factory
    ☆ [HDU4825] Xor Sum「最大异或和(Trie树)」
    「网络流24题」最长不下降子序列问题
    「网络流24题」试题库问题
  • 原文地址:https://www.cnblogs.com/weiyi-mgh/p/6434338.html
Copyright © 2011-2022 走看看