字节笔试题: 根据前序和中序遍历,求二叉树的叶子节点数

题目描述:
二叉树的叶子节点数
给定一颗二叉树,二叉树每个节点都有唯一正整数代表节点,在遍历时,使用节点的整数值作为标记。
输入:二叉树的节点个数,前序和中序遍历结果,分别是第一行、第二行和第三行;
输出:二叉树叶子节点的个数
输入描述:
第一行:输入二叉树节点个数N, 0 < N < 30000
第二行:前序遍历
第三含:中序遍历

示例:
输入:
3
1 3 4
3 1 4
输出:
2

求解思路:
根据二叉树的前序和中序遍历,构建二叉树;最后求出二叉树叶子节点的个数。
代码:

#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;

struct node
{
    
    
	int c;
	struct node *lch, *rch;
};

//统计叶子结点
int count_leaf(node* tree);
//构建二叉树
void create_tree(int* l, int* r, int i, int j, int e, int f, node** tree);
int main()
{
    
    
	node *tree;
	int *pre;
	int *in;
	int n;
	cin >> n;

	pre = (int *)malloc(sizeof(int) *(n + 1));
	in = (int *)malloc(sizeof(int) *(n + 1));

	for (int i = 0; i < n; ++i)
		cin >> pre[i];
	for (int i = 0; i < n; ++i)
		cin >> in[i];
	create_tree(pre, in, 0, n - 1, 0, n - 1, &tree);
	cout << count_leaf(tree) << endl;
	return 0;
}
int count_leaf(node* tree)
{
    
    
	if (tree == NULL)  return 0;
	if (tree->lch == NULL&&tree->rch == NULL)    return 1;
	return count_leaf(tree->lch) + count_leaf(tree->rch);
}

void create_tree(int* l, int* r, int i, int j, int e, int f, node** tree)
{
    
    
	int m;
	(*tree) = new node;
	(*tree)->c = l[i];
	m = e;
	while (r[m] != l[i])    m++;
	if (m == e)    (*tree)->lch = NULL;
	else    create_tree(l, r, i + 1, i + m - e, e, m - 1, &(*tree)->lch);
	if (m == f)    (*tree)->rch = NULL;
	else    create_tree(l, r, i + m - e + 1, j, m + 1, f, &(*tree)->rch);
}

猜你喜欢

转载自blog.csdn.net/changyi9995/article/details/108037817