Binary tree establishment, traversal, leaf node count, depth calculation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.