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

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

 

二叉树节点数据结构:

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

 

posted @ 2017-02-23 16:59  糯米米一粒  阅读(302)  评论(0编辑  收藏  举报