以二叉鏈表作為二叉樹的存儲結構,求二叉樹的葉子結點個數。
輸入格式:
輸入二叉樹的先序序列。
提示:一棵二叉樹的先序序列是一個字符串,若字符是‘#’,表示該二叉樹是空樹,否則該字符是相應結點的數據元素。
輸出格式:
輸出有兩行:
第一行是二叉樹的中序遍歷序列;
第二行是二叉樹的葉子結點個數。
輸入樣例:
ABC##DE#G##F###
輸出樣例:
CBEGDFA
3
代碼:
#include <stdio.h> #include <stdlib.h> #include <string.h> char a[1000]; int ant = 0,c = 0; typedef struct Node { char Data; struct Node *Left,*Right; }Node; Node *CreatNode() { Node *p = (Node *)malloc(sizeof(Node)); p -> Left = p -> Right = NULL; return p; } Node *CreatTree() { if(a[ant] == '#') { ant ++; return NULL; } Node *head = CreatNode(); head -> Data = a[ant ++]; head -> Left = CreatTree(); head -> Right = CreatTree(); if(head -> Left == NULL && head -> Right == NULL)c ++; return head; } void InOrder(Node *T) { if(T == NULL)return; InOrder(T -> Left); putchar(T -> Data); InOrder(T -> Right); } int main() { scanf("%s",a); Node *head = CreatTree(); InOrder(head); putchar('\n'); putchar('0'+c); }