二叉树遍历应用

#include<stdio.h>
#include<malloc.h>
#include<string.h>

typedef struct BNode{
char data;
struct BNode *left;
struct BNode *right;
}BNode;

char str[101]; //存放输入的先序遍历字符串
int i;
BNode *Insert(){
if(str[i] == '#'){ //空结点,注意单个字符用' '而不能用" "
i++;
return NULL;
}else{
//新建一个结点
BNode *root = (BNode *)malloc(sizeof(BNode));
root->data = str[i];
root->left = NULL;
root->right = NULL;
i++;
root->left = Insert();
root->right = Insert();
return root;
}
}

void inOrder(BNode *root){
if(root->left != NULL){
inOrder(root->left);
}
printf("%c ",root->data);
if(root->right != NULL){
inOrder(root->right);
}
}

int main(){
while(scanf("%s",str) != EOF){
i = 0;
BNode *root = Insert();
inOrder(root);
}
return 0;
}

posted @ 2023-11-19 23:33  涨涨涨张  阅读(2)  评论(0编辑  收藏  举报