方法一:
前序遍历
先从根出发,然后就一直走左子树,然后递归回溯 一颗二叉树就建好了 然后再中序遍历
记得要开辟数组来储存不为#的符号
AC代码:
#include#include #include typedef struct TreeNode { char data; struct TreeNode*left; struct TreeNode*right; }BTNode; BTNode*BuyNode(char x) { BTNode*newnode=(BTNode*)malloc(sizeof(BTNode)); newnode->data=x; newnode->left=NULL; newnode->right=NULL; return newnode; } BTNode*CreatTree(char *str,int *i) { if(str[*i]=='#') { (*i)++; return NULL; } BTNode*root=BuyNode(str[(*i)++]); root->left=CreatTree(str,i); root->right=CreatTree(str,i); return root; } void InOrder(BTNode*root) { if(root==NULL) return; InOrder(root->left); printf("%c ",root->data); InOrder(root->right); } int main() { char str[100]; scanf("%s",str); int i=0; BTNode*root=CreatTree(str,&i); InOrder(root); return 0; }
如有错误,多多指教!



