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);
        }
    }
    
  • 相关阅读:
    springmvc+mybatis多数据源切换
    Tomcat 8.5 配置自动从http跳转https
    Tomcat 8.5 配置 域名绑定
    本地测试Tomcat配置Https访问
    Spring boot
    解决IDEA16闪退的问题
    cef
    spring-boot学习资料
    oracle 表空间不足解决办法
    oracle导出表的办法
  • 原文地址:https://www.cnblogs.com/weiyi-mgh/p/6434338.html
Copyright © 2011-2022 走看看