Directly on the code, there are empty explanations
Note that this is a way to build the first order
Sampleinput
abd*f***ce***
Output
First-order traversal results
Abdfce
Middle Sequence Traversal results
Dfbaec
Post-sequential traversal results
Fdbeca
The depth of the tree is 4
The number of leaf nodes is 2
#include <string.h>#include<stdlib.h>#include<stdio.h>#include<malloc.h>#include<iostream>using namespacestd;structnode{Chardata; structNode *l, *R;};intsum =0;structNode *creat (structNode *p) { CharQ; scanf ("%c", &q); if(q = =' *') P=NULL; Else{p= (structNode *) malloc (sizeof(structNode)); P->data =Q; P->l = creat (p->l); P->r = creat (p->R); } returnp;}intXianxu (structNode *p) { if(p) {printf ("%c", p->data); Xianxu (P-l); Xianxu (P-R); } return 0;}intZhongxu (structNode *p) { if(P) {Zhongxu (P-l); printf ("%c", p->data); Zhongxu (P-R); } return 0;}intHouxu (structNode *p) { if(P) {Houxu (P-l); Houxu (P-R); printf ("%c", p->data); } return 0;}intDeep (structNode *p) { intC1, C2; if(!p)return 0; C1= Deep (p->l); C2= Deep (p->R); returnC1 > C2? c1+1: c2+1;}intJiedian (structNode *p) { if(P) {Jiedian (P-l); Jiedian (P-R); if((p->l = = NULL) && (P->r = =NULL)) Sum++; } returnsum;}intMain () {intsum; structNode *Head; Head= (structNode *) malloc (sizeof(structNode)); Head=creat (head); printf ("First order traversal result \ n"); Xianxu (head); printf ("\ n"); printf ("Middle sequence traversal result \ n"); Zhongxu (head); printf ("\ n"); printf ("Post-post traversal results \ n"); Houxu (head); printf ("\ n"); printf ("the depth of the tree is%d\n", Deep (head)); Sum=Jiedian (head); printf ("the number of leaf nodes is%d\n", sum); return 0;}
Binary tree establishment, traversal, leaf node count, depth calculation