题解 | #二叉树遍历#
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
#include <stdlib.h> #include <stdio.h> #include <string.h> #define len 2000 typedef struct node{ char val; struct node*lchild; struct node*rchild; }node; node*initial_node(char c){ node*nd = (node*)malloc(sizeof(node)); nd->val = c; nd->lchild = NULL; nd->rchild = NULL; return nd; } int i; node*build_tree(char str[]){ i++; if(str[i]!='#'&&i<strlen(str)){ node*nd = initial_node(str[i]); nd->lchild = build_tree(str); nd->rchild = build_tree(str); return nd; } return NULL; } void LNR(node*tree){ if(tree!=NULL){ LNR(tree->lchild); printf("%c ",tree->val); LNR(tree->rchild); } } int main(){ char str[len]; while(scanf("%s",str)!=EOF){ i = -1; node*tree = build_tree(str); LNR(tree); printf("\n"); } }