6-9 先序建树层次遍历 (25 分)
编写程序,要求实现(1)按先序遍历序列建立二叉树的二叉链表;(2)按层次遍历二叉树。
构成二叉链表的结点类代码如下:
class BtNode{
char data;
BtNode lchild,rchild;
}
按加入空树信息的先序遍历序列建立二叉树的二叉链表代码提供如下:
//先序遍历序列建立二叉链表
public static BtNode createBiTree() throws IOException{
char c=(char) System.in.read();
if(c=='#'){
return null;
}else{
BtNode bt=new BtNode();
bt.data=c;
bt.lchild=createBiTree();
bt.rchild=createBiTree();
return bt;
}
}
输入格式:
输入一棵二叉树的加入空树信息的先序遍历序列,以#字符表示空树。
输出格式:
输出二叉树的层次遍历的序列。
输入样例:
ab#c##d##
输出样例:
abdc
#include<iostream>
using namespace std;
typedef struct node* position;
typedef position tree;
struct node {
char data;
node* left;
node * right;
};
node* createTree() {
char c;
cin >> c;
if (c == '#')
return NULL;
else {
tree BT = (tree)malloc(sizeof(struct node));
BT->data = c;
BT->left = createTree();
BT->right = createTree();
return BT;
}
}
void LevelorderTraversal(tree BT) {
if (BT == NULL) return;
tree f[10000] = { NULL };
int t = -1;
f[++t] = BT;
int i = 0;
while (f[i] != NULL) {
if (f[i]->left != NULL) f[++t] = f[i]->left;
if (f[i]->right != NULL) f[++t] = f[i]->right;
i++;
}
for (int j = 0; j <= t; j++)
cout << f[j]->data;
}
int main() {
tree f;
f = createTree();
LevelorderTraversal(f);
return 0;
}