设置算法将一棵以二叉链表存储到一个一维数组中

#include<stdio.h>
#include<iostream>
#include<queue>
#include<stdlib.h>
using namespace std;
#define maxn 1000
struct node
{
    char  v;
    struct node*ls,*rs;
}tree[maxn];//最多存树的1000个节点
int num=0;//num表示节点的编号,从0开始计数
struct node*build()
{
    char ch;
    cin>>ch;
    if(ch=='#') return NULL;
    struct node*p=(struct node*)malloc(sizeof(struct node));
    p->v=ch;
    p->ls=build();
    p->rs=build();
    return p;
};
void store(struct node*head)
{
    queue<struct node>q;
    q.push(*head);
    while(!q.empty())
    {
        struct node now=q.front();
        q.pop();
        num++;
        tree[num]=now;
        if(now.ls) q.push(*(now.ls));
        if(now.rs) q.push(*(now.rs));


    }
}
int main()
{
    struct node*head;
    head=build();
    store(head);
    for(int i=1;i<=num;i++)
        cout<<"index:"<<i<<" 节点的value:"<<tree[i].v<<endl;
    return 0;
}

原文地址:https://www.cnblogs.com/eason9906/p/11755128.html