前序+后序=〉(二叉)树的个数
来源:互联网 发布:ubuntu mediawiki 编辑:程序博客网 时间:2024/06/06 09:41
假设前序序列为pre,后序序列为post,他们的长度分别为n,必有:
pre[0]==post[n-1],同时pre[1]为根节点的第一颗子树的根节点,再post中查找pre[1],这样就可以判定出该树的第一颗子树的前序序列和后序序列。同样的道理,可以判断出该树的所有子树的前序和后序序列。递归解之。代码如下:
#include <iostream>
#include <string>
using namespace std;
long process(int m, string pre, string post)
{
if (pre.substr(0,1) != post.substr(post.length()-1,1))
return 0;
if (pre.length() == 1)
return 1;
long ans = 1;
pre = pre.substr(1, pre.length());
post = post.substr(0, post.length()-1);
int numchild = 0;
long comb = 1;
while (pre.length() > 0) {
numchild++;
int index = post.find(pre[0]);
string newPost = post.substr(0, index+1);
post = post.substr(index+1, post.length());
string newPre = pre.substr(0, index+1);
pre = pre.substr(index+1, pre.length());
ans *= process(m, newPre, newPost);
if (ans == 0)
return 0;
comb = comb*(m-numchild+1)/numchild;
}
return ans*comb;
}
int main()
{
string post, pre;
int m;
cin >> m;
while (m != 0) {
cin >> pre >> post;
if (pre.length() != post.length())
cout << 0 << endl;
else
cout << process(m, pre, post) << endl;
cin >> m;
}
}
#include <string>
using namespace std;
long process(int m, string pre, string post)
{
if (pre.substr(0,1) != post.substr(post.length()-1,1))
return 0;
if (pre.length() == 1)
return 1;
long ans = 1;
pre = pre.substr(1, pre.length());
post = post.substr(0, post.length()-1);
int numchild = 0;
long comb = 1;
while (pre.length() > 0) {
numchild++;
int index = post.find(pre[0]);
string newPost = post.substr(0, index+1);
post = post.substr(index+1, post.length());
string newPre = pre.substr(0, index+1);
pre = pre.substr(index+1, pre.length());
ans *= process(m, newPre, newPost);
if (ans == 0)
return 0;
comb = comb*(m-numchild+1)/numchild;
}
return ans*comb;
}
int main()
{
string post, pre;
int m;
cin >> m;
while (m != 0) {
cin >> pre >> post;
if (pre.length() != post.length())
cout << 0 << endl;
else
cout << process(m, pre, post) << endl;
cin >> m;
}
}
- 前序+后序=〉(二叉)树的个数
- 知道前序序列和后序序列求二叉树的个数+大数
- 二叉树的前、中、后序遍历(递归和非递归)、层序遍历、深度、叶子节点个数
- 二叉树建立、遍历(前序,中序,后序),求叶节点个数,求节点个数
- 二叉树的遍历(前、中、后序)
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 二叉树的前序、中序、后序遍历
- 二叉树的遍历(前序,中序,后序)
- 二叉树的遍历:前序、中序、后序
- 二叉树的前序、中序、后序遍历
- 二叉树的前序、中序、后序遍历
- Turbo C# C++2006
- Turbo Delphi for .NET 2006
- 刚学java
- 文件自启动方式
- 比较郁闷的问题
- 前序+后序=〉(二叉)树的个数
- SET IDENTITY_INSERT的用法
- SQL笔记__分页存储过程
- 五大内存分区,堆与栈的区别
- 猫猫登场,全体鼓掌 /^O^/
- 关于学习VB语言的感受060906
- 自动刷新网页(转载+整理)
- SET CONCAT_NULL_YIELDS_NULL的用法
- 函数指针