二叉树 先根/中根/后根/层级 递归/非递归 周游的总结C++

5 篇文章 0 订阅

观前提示:代码没有注释,里面有很多是参考别人的代码,算是备忘录。

先是我二叉树的实现方式:

class node
{
public:
    int info;
    node *lLink, *rLink;
    node(int _info) : info(_info), lLink(NULL), rLink(NULL) {}
};

然后是周游算法:

// 递归实现
void preOrder(node *root)
{
    if (root == NULL) return;
    cout << root->info << ",";
    preOrder(root->lLink);
    preOrder(root->rLink);
}

void inOrder(node *root)
{
    if (root == NULL) return;
    inOrder(root->lLink);
    cout << root->info << ",";
    inOrder(root->rLink);
}

void postOrder(node *root)
{
    if (root == NULL) return;
    postOrder(root->lLink);
    postOrder(root->rLink);
    cout << root->info << ",";
}

// 非递归实现
void PreOrder(node *root)
{
    stack<node *> s;
    s.push(root);
    while (!s.empty())
    {
        node *cur = s.top();
        s.pop();
        cout << cur->info << ",";
        if (cur->rLink)
            s.push(cur->rLink);
        if (cur->lLink)
            s.push(cur->lLink);
    }
    cout << endl;
}

void InOrder(node *root)
{
    stack<node *> s;
    node *cur = root;
    while (cur || !s.empty())
    {
        while (cur)
        {
            s.push(cur);
            cur = cur->lLink;
        }
        cur = s.top();
        s.pop();
        cout << cur->info << ",";
        cur = cur->rLink;
    }
    cout << endl;
}

void PostOrder(node *root)
{
    stack<node *> s;
    node *cur = root, *pre = NULL;
    while (cur || !s.empty())
    {
        while (cur)
        {
            s.push(cur);
            cur = cur->lLink;
        }
        cur = s.top();
        s.pop();
        if (cur->rLink == NULL || cur->rLink == pre)
        {
            cout << cur->info << ",";
            pre = cur;
            cur = NULL;
        }
        else
        {
            s.push(cur);
            cur = cur->rLink;
        }
    }
    cout << endl;
}

void LevelOrder(node *root)
{
    queue<node *>q;
    q.push(root);
    while (!q.empty())
    {
        node *cur = q.front();
        q.pop();
        cout << cur->info << ",";
        if (cur->lLink)
            q.push(cur->lLink);
        if (cur->rLink)
            q.push(cur->rLink);
    }
    cout << endl;
}

想要调用的话就这样子:

int main()
{
    node *root = new node(0);
    root->lLink = new node(1);
    root->rLink = new node(2);
    root->lLink->rLink = new node(3);
    root->rLink->lLink = new node(4);
    root->rLink->rLink = new node(5);

    // 递归周游
    preOrder(root);
    cout << endl;
    inOrder(root);
    cout << endl;
    postOrder(root);
    cout << endl;

    // 非递归周游
    PreOrder(root);
    InOrder(root);
    PostOrder(root);
    LevelOrder(root);
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值