统计利用先序遍历创建的二叉树的度为1的结点个数

统计利用先序遍历创建的二叉树的度为1的结点个数

1000(ms)

10000(kb)

2793 / 4606

利用先序递归遍历算法创建二叉树并计算该二叉树度为1结点的个数。先序递归遍历建立二叉树的方法为:按照先序递归遍历的思想将对二叉树结点的抽象访问具体化为根据接收的数据决定是否产生该结点从而实现创建该二叉树的二叉链表存储结构。约定二叉树结点数据为单个大写英文字符。当接收的数据是字符"#"时表示该结点不需要创建,否则创建该结点。最后再统计创建完成的二叉树度为1的结点个数。需要注意输入数据序列中的"#"字符和非"#"字符的序列及个数关系,这会最终决定创建的二叉树的形态。

输入

输入为接受键盘输入的由大写英文字符和"#"字符构成的一个字符串(用于创建对应的二叉树)。

输出

每个用例用一行输出该用例对应的二叉树度为1的结点个数。

样例输入

#
A##
ABC####
AB##C##
ABCD###EF##G###
A##B##
#A

样例输出

0
0
2
0
2
0
0
#include <iostream>
#include <list>
#include <algorithm>
#include <stack>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <queue>
#include <stack>
using namespace std;

typedef struct node{
    char data;
    struct node *left;
    struct node *right;
}BTNode;
int createBT(BTNode *&p){
   char ch;
   cin>>ch;
   if(ch == '#'){
     p==NULL;
     return 0;
   }
   else{
     p = (BTNode*)malloc(sizeof(BTNode));
     p->data = ch;
     p->left = NULL;
     p->right =NULL;
     int t = createBT(p->left);
     int t1 = createBT(p->right);
     if((p->left == NULL && p->right!=NULL) || (p->right == NULL&&p->left!=NULL)){
        return t+t1+1;
     }
     return t+t1;
   }
}
int main()
{
   BTNode *head ;
   int res = createBT(head);
   cout<<res;
   return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_30092289/article/details/89054462