题解 | #二叉树遍历#
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
#include <stdio.h> #include <stdlib.h> //创建二叉树 typedef struct TreeNode { struct TreeNode* left; struct TreeNode* right; char val; }TNode; //前序生成二叉树 TNode* CreatTree(char *s,int *i) { if(s[*i]=='#') { (*i)++; return NULL; } TNode* root=(TNode*)malloc(sizeof(TNode)); if(root==NULL) { printf("mallloc failed!\n"); exit(-1); } root->val=s[*i]; (*i)++; root->left=CreatTree(s,i); root->right=CreatTree(s, i); return root; } # 中序打印二叉树 void InOrder(TNode* root) { if(root==NULL) { return; } InOrder(root->left); printf("%c ",root->val); InOrder(root->right); } int main() { char str[100]; scanf("%s",str); int i=0; TNode* root=CreatTree(str, &i); InOrder(root); return 0; }#数据结构和算法#