二叉树的序遍历

先说一下最基本的概念:

前序遍历:根->左孩子->右孩子。

中序遍历:左孩子->根->右孩子。

后序遍历:左孩子->右孩子->根。


然后是二叉树的存储方式。这里用的是用数组存储二叉树。

先开一个tree[]数组,tree[1]为二叉树的根节点,非零表示存在该节点,反之不存在。对于tree[i],它的左孩子为tree[2*i],右孩子为tree[2*i+1]。


下面祭上三种遍历的代码:

void first(int i)
{
    cout << tree[i] << " ";
    if(tree[i * 2] != 0)
        first(i * 2);
    if(tree[i * 2 + 1] != 0)
        first(i * 2 + 1);
}
void mid(int i)
{
    if(tree[i * 2] != 0)
        mid(i * 2);
    cout << tree[i] << " ";
    if(tree[i * 2 + 1] != 0)
        mid(i * 2 + 1);
}
void last(int i)
{
    if(tree[i * 2] != 0)
        last(i * 2);
    if(tree[i * 2 + 1] != 0)
        last(i * 2 + 1);
    cout << tree[i] << " ";
}
可以看出,非常简单。。。

code[vs]-3143:http://www.codevs.cn/problem/3143/

祭上题解:

i表示整体二叉树的框架,tree[i]数组存第i个节点是第tree[i]个点,用mp[xc]存第xc个节点是第mp[xc]个点。

#include <iostream>
#include <map>
using namespace std;
int tree[101];
map<int, int> mp;
void first(int i)
{
    cout << tree[i] << " ";
    if(tree[i * 2] != 0)
        first(i * 2);
    if(tree[i * 2 + 1] != 0)
        first(i * 2 + 1);
}
void mid(int i)
{
    if(tree[i * 2] != 0)
        mid(i * 2);
    cout << tree[i] << " ";
    if(tree[i * 2 + 1] != 0)
        mid(i * 2 + 1);
}
void last(int i)
{
    if(tree[i * 2] != 0)
        last(i * 2);
    if(tree[i * 2 + 1] != 0)
        last(i * 2 + 1);
    cout << tree[i] << " ";
}
int main()
{
    tree[1] = 1;
    mp[1] = 1;
    int n, lc, rc;
    cin >> n;
    for(int i = 1; i <= n; i++)
    {
        cin >> lc >> rc;
        int va = mp[i];
        tree[2 * va] = lc;
        mp[lc] = 2 * va;
        tree[2 * va + 1] = rc;
        mp[rc] = 2 * va + 1;
    }
    first(1);
    cout << endl;
    mid(1);
    cout << endl;
    last(1);
    cout << endl;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值