顺序存储转为链接存储(二叉树)

来源:互联网 发布:mac rar文件 编辑:程序博客网 时间:2024/05/24 22:44

1.题目:

 Problem Description

设有一棵二叉树,其节点值为字符型并假设各值互不相等,采用顺序存储表示。现输入其数组各元素值(空二叉树用'#'表示),建立该二叉树,要求将该二叉树的顺序存储结构转换为二叉链表存储结构,并输出其前序遍历序列。


 Input

第一行为一个整数n,表示以下有n组数据,每组数据占一行,为其数组各元素值(空二叉树用'#'表示),每组数据长度不超过50。


 Output

输出该二叉树的前序遍历序列,空二叉树则不输出任何信息。


 Sample Input

2ABC#DABCDE#F


 Sample Output

ABDCABDECF

2.参考代码:

#include <iostream>#include <string.h>using namespace std;char str[111];struct BiNode{char data;BiNode* lchild,* rchild;};BiNode* Creat(int i,int n){BiNode* root=new BiNode;root->data=str[i];root->lchild=root->rchild=NULL;   ///把左右孩子初始化为空,因为在前序遍历///的时候会判断当前结点是否为空,不为空的话,它的data域才有值,然后才要输出。if(2*i<=n)root->lchild=Creat(2*i,n);   ///建立左子树if(2*i+1<=n)root->rchild=Creat(2*i+1,n);   ///建立右子树return root;}void PreOrder(BiNode* root){if(root==NULL)return ;else{if(root->data!='#')cout<<root->data;PreOrder(root->lchild);PreOrder(root->rchild);}}int main(){int n,len;cin>>n;while(n--){cin>>str+1;len=strlen(str+1);if(str[1]=='#')   ///如果第一个为#号则继续continue;BiNode* root=Creat(1,len);PreOrder(root);cout<<endl;}return 0;}






原创粉丝点击