目录
L4-202 二叉搜索树的2层结点统计 - 构建二叉搜索树板子
L2-041 插松枝 - 栈 + 队列 + 模拟
#include <bits/stdc++.h>
using namespace std;
const int N=1010;
vector<int> res;
int n,m,k,pre;
int main()
{
stack<int> stk;
queue<int> q;
int cnt=0; //cnt根松枝已经有归属
cin>>n>>m>>k;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
q.push(x);
}
while(1)
{
if(cnt==n&&stk.empty()) break; //如果所有松枝都有归属 且 盒子里无松枝
res.clear();
pre=110;
while(!stk.empty()&&stk.top()<=pre)
{
int x=stk.top();
if(res.size()>=k) break;
pre=x;
cnt++; //该松枝已有归属
res.push_back(x);
stk.pop();
}
while(!q.empty()) //在推进器取松针
{
if(res.size()<k) //如果松枝未插满
{
if(q.front()<=pre) //如果松针长度≤上一根长度
{
pre=q.front();
cnt++;
res.push_back(pre);
q.pop();
}else if(stk.size()<m) //如果不满足要求 且小盒子还能放 放小盒子
{
stk.push(q.front());
q.pop();
}else break;
}else break;
}
for(int i=0;i<res.size();i++)
{
if(i!=0) cout<<" ";
cout<<res[i];
}
cout<<endl;
}
}
L4-205 浪漫侧影 - 中后序建树 + bfs层序遍历
思路:
第一步:建树
- left存左孩子 right存右孩子
- idx存节点x在中序遍历的下标
- 通过dfs建树,刚开始后序和中序遍历的范围均为[0~n-1]
- 后序遍历范围【l1,r1】 中序遍历范围【l2,r2】
- 每棵子树的根节点为r1
- k=idx[root]找出该根节点在中序遍历的下标
- 递归分别建立左子树和右子树