今天晚上没啥事,洗了洗澡,吃了点东西,又写了一道,感觉和上一道比较类似。
题目如下:
分析一下题目,它是将一个先序的一串数据整到二叉树里,再找出它的叶节点有几个。
输入我决定采用递归的方法,每次读入一个数据,若是字母说明他是一个根节点,若是‘#’说明上个节点没有当前分支,返回NULL即可。由此,AB###可转换成如下二叉树:
寻找叶子节点我也选择递归的方法,如果这个节点的左右支都为NULL,就是个叶节点,直接返回1就可以,否则就依次寻找左支和右支内的叶节点数,返回总结点数,构成递归,如下图:
以下是我的实现:
#include <stdio.h> #include <stdlib.h> struct binaryTree { char data; struct binaryTree *left; struct binaryTree *right; }; void run (); struct binaryTree *createNewBinaryTree (); int getAmountOfLeaf (struct binaryTree *head); int main() { run (); return 0; } struct binaryTree *createNewBinaryTree () { char s; struct binaryTree *cur; s=getchar (); if (s>='A'&&s<='Z') { cur=(struct binaryTree*)malloc(sizeof(struct binaryTree)); cur->data=s; cur->left=createNewBinaryTree (); cur->right=createNewBinaryTree (); return cur; } else { return NULL; } } void run () { int n; struct binaryTree *head; head=createNewBinaryTree (); n=getAmountOfLeaf (head); printf ("%d",n); } int getAmountOfLeaf (struct binaryTree *head) { int nLeft=0,nRight=0; if (head->left==NULL&&head->right==NULL) { return 1; } if (head->left) { nLeft=getAmountOfLeaf (head->left); } if (head->right) { nRight=getAmountOfLeaf (head->right); } return nLeft+nRight; }
下面是各函数的注释:
struct binaryTree *createNewBinaryTree () { char s; struct binaryTree *cur; s=getchar ();//读入数据 if (s>='A'&&s<='Z')//若是字母 { cur=(struct binaryTree*)malloc(sizeof(struct binaryTree));//创建节点并赋值 cur->data=s; cur->left=createNewBinaryTree ();//左支递归 cur->right=createNewBinaryTree ();//右支递归 return cur;//返回当前节点,便于递归 } else//若是‘#’ { return NULL; } }
int getAmountOfLeaf (struct binaryTree *head) { int nLeft=0,nRight=0; if (head->left==NULL&&head->right==NULL)//若是叶节点 { return 1; } if (head->left)//若左支存在 { nLeft=getAmountOfLeaf (head->left);//递归左支 } if (head->right)//同上 { nRight=getAmountOfLeaf (head->right); } return nLeft+nRight;//返回该节点分支中的叶节点总数 }以上就是我的实现,希望给大家带来帮助