直接上代码,可以直接运行。
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
#include <stdbool.h>
/**二叉树数据结构定义**/
struct treenode
{
char val;
struct treenode *left;
struct treenode *right;
}treenode;
//建立二叉树
struct treenode* build_tree(char* s,int i)
{
if(i>=strlen(s))return NULL;
if(s[i]=='#')return NULL;
//printf("%d\n",i);
struct treenode* root=(struct treenode*)malloc(sizeof(treenode));
root->val=s[i];
if(2*i+1<strlen(s))root->left=build_tree(s,2*i+1);
else root->left=NULL;
if(2*i+2<strlen(s))root->right=build_tree(s,2*i+2);
else root->right=NULL;
return root;
}
//先根递归遍历
void preOrder(struct treenode* root)
{