求二叉树的叶子结点个数
题目:以二叉链表作为二叉树的存储结构,求二叉树的叶子结点个数。
输入格式:
输入二叉树的先序序列。
提示:一棵二叉树的先序序列是一个字符串,若字符是‘#’,表示该二叉树是空树,否则该字符是相应结点的数据元素。
输出格式:
输出有两行:
第一行是二叉树的中序遍历序列;
第二行是二叉树的叶子结点个数。
输入样例:
ABC##DE#G##F###
输出样例:
CBEGDFA
3
#include <iostream>
using namespace std;
int leaf_node = 0; // 记住叶子结点个数
struct BinaryTree_Node
{
char value; // 节点的值
BinaryTree_Node* lChild; // 左子节点
BinaryTree_Node* rChild; // 右子节点
// 节点的构造函数
BinaryTree_Node(): lChild(NULL), rChild(NULL)
{
}
};
typedef BinaryTree_Node* BT_Node;
// 创建二叉树 (先序遍历)
BT_Node Create_BinaryTree()
{
BT_Node root = new BinaryTree_Node();
char v;
cin >> v;
if (v != '#')
{
root->value = v;
root->lChild = Create_BinaryTree();
root->rChild = Create_BinaryTree();
if (root->lChild == NULL && root->rChild == NULL)
leaf_node++;
}
else
root = NULL;
return root;
}
// 中序遍历
void In_traverse(BT_Node root)
{
if (root == NULL)
return;
In_traverse(root->lChild);
cout << root->value;
In_traverse(root->rChild);
}
int main()
{
BT_Node root;
root = Create_BinaryTree();
In_traverse(root);
cout << endl;
cout << leaf_node;
}