1366:二叉树输出(btout)

【算法分析】

        s1是前序遍历字符串,s2是中序遍历字符串。构造一个函数build(int l1,int r1,int l2,int r2),通过在s2中找s1的第一个节点,也就是根节点,把它赋值给p,把s1分成左右子树。左子树是l1+1到l1+p-l2,右子树是l1+p-l2+1到r1。s2的左子树是l2到p-1,右子树是p+1到r2。
        如果p>l2,递归调用build(l1+1,l1+p-l2,l2,p-1),如果p<r2,递归调用build(l1+p-l2+1,r1,p+1,r2)。累加到c[l1],直到叶子结点,c[l1]=1。这样就可以统计出每个节点的有多少个叶子结点。
       然后通过循环遍历s1,输出每个节点重复的值。

【参考代码】

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
string s1,s2;
int c[205];
int build(int l1,int r1,int l2,int r2){
	if(l1==r1){//到达叶子
		c[l1]=1;return c[l1];
	}
	int p=s2.find(s1[l1]);
	if(p>l2) c[l1]+=build(l1+1,l1+p-l2,l2,p-1);
	if(p<r2) c[l1]+=build(l1+p-l2+1,r1,p+1,r2);
	return c[l1];
}
int main()
{
	cin>>s1>>s2;
	build(0,s1.length()-1,0,s2.length()-1);
	for(int i=0;i<s1.length();i++){
		for(int j=1;j<=c[i];j++) cout<<s1[i];
		cout<<endl;
	}
    return 0;
}

find()函数


相关推荐

  1. 1364遍历(flist)

    2024-04-09 05:58:01       13 阅读
  2. 1368:对称(tree_c)

    2024-04-09 05:58:01       16 阅读
  3. Leetcode 1367. Linked List in Binary Tree (好题)

    2024-04-09 05:58:01       30 阅读
  4. 7-136 后序和中序构造

    2024-04-09 05:58:01       12 阅读
  5. 本地由LeetCode输入构建(C++版)

    2024-04-09 05:58:01       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-09 05:58:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-09 05:58:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-09 05:58:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-09 05:58:01       20 阅读

热门阅读

  1. 【uniapp小程序-跳转另一个小程序】

    2024-04-09 05:58:01       14 阅读
  2. el-table-column 有两个input怎么校验

    2024-04-09 05:58:01       14 阅读
  3. Day7:学习尚上优选项目

    2024-04-09 05:58:01       14 阅读
  4. 神经网络中的权重初始化

    2024-04-09 05:58:01       14 阅读
  5. 速盾:前端挂载到cdn托管

    2024-04-09 05:58:01       13 阅读
  6. 微服务架构与面向服务架构

    2024-04-09 05:58:01       12 阅读
  7. WebKit架构简介:深入探索与代码实例分析

    2024-04-09 05:58:01       13 阅读
  8. SQL注入---HTTP报头注入

    2024-04-09 05:58:01       14 阅读
  9. HI-8445PSIF-10 一款四通道ARINC429线路接收器ic

    2024-04-09 05:58:01       12 阅读
  10. 第9章 视图view

    2024-04-09 05:58:01       11 阅读