码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的前中后序遍历简单的递归

时间:2017-02-23 17:20:25      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:nod   结构   str   eve   node   nullptr   广度   pos   class   

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

 

二叉树节点数据结构:

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);
    }
}

 

二叉树的前中后序遍历简单的递归

标签:nod   结构   str   eve   node   nullptr   广度   pos   class   

原文地址:http://www.cnblogs.com/weiyi-mgh/p/6434338.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!