题解 | #二叉树遍历#
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
#include <stdio.h> #include <stdlib.h> struct TreeNode { char val; struct TreeNode* left; struct TreeNode* right; }; struct TreeNode* CreatTree(char* a,int* pi) { if(a[*pi]=='\0')//判断是否走完 { return NULL; } if(a[*pi]=='#')//判断空 { (*pi)++; return NULL; } //不为空则创建一个树节点,赋值 struct TreeNode* root=(struct TreeNode*)malloc(sizeof(struct TreeNode)); root->val=a[(*pi)++]; //递归 root->left=CreatTree(a,pi); root->right=CreatTree(a,pi); return root; } void Inorder(struct TreeNode* root)//中序遍历并打印 { if(root==NULL) { return; } Inorder(root->left); printf("%c ",root->val); Inorder(root->right); } int main() { char a[100]; scanf("%s",a); int i=0; struct TreeNode* root=CreatTree(a,&i); Inorder(root); return 0; }