#include <cstdio>
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
const int maxn = 10000 + 1;
int ltree[maxn], rtree[maxn], in_order[maxn], post_order[maxn];
int n;//n用于统计先序遍历与后序遍历数组中相应元素
bool read(int *a)
{
string line;//按行读取,注意利用stringstream输入流的处理
if (!getline(cin, line))//处理读入结束
return false;
stringstream ss(line);
n = 0;
int record;//用于记录该行中每个读入的数
while (ss >> record)a[n++] = record;
return n > 0;
}
int build(int L1,int R1,int L2,int R2)//注意返回二叉树的根节点
{//R2用于控制后序遍历中读取根节点
if (L1 > R1)
return 0;//注意建树时左右的控制
int p = L1;
int root = post_order[R2];//利用后序遍历首先找到根节点,之后再到中序遍历中寻找相应节点进行递归建树
while (in_order[p] != root)p++;
int count = p - L1;//分为左右子树再进行递归寻找
ltree[root] = build(L1, p - 1, L2, L2 + count - 1);//L2+count-1用于寻找后序遍历中根节点的位置
rtree[root] = build(p + 1, R1, L2+count, R2 - 1);//注意后序遍历中根节点位置的控制,细节
return root;
}
int best, best_sum;//记录最好路径以及最好的叶子结点
void dfs(int u,int sum)//深度优先搜索
{
sum += u;
if (!ltree[u] && !rtree[u])//到达最底层,即到达叶子结点
{
if (sum < best_sum)
{
best = u; best_sum = sum;
}
}
if (ltree[u])//左右子树分别递归寻找最佳方案
dfs(ltree[u],sum);
if (rtree[u])
dfs(rtree[u], sum);
}
int main()
{
while (read(in_order))
{
read(post_order);
build(0, n - 1, 0, n - 1);//进行建树的操作
best_sum = 1000000000;
dfs(post_order[n - 1], 0);//从根节点开始寻找最佳路径
cout << best << endl;
}
getchar();
getchar();
return 0;
}
1、此题重点理解二叉树中几种遍历方式的特点,注意中序遍历与后序遍历的特点
2、二叉树中注意重点理解其递归的特性,利用两种遍历方式特点,进行递归建树的操作,递归寻找相应节点,在建立左子树与右子树,数组中存储下一节点的权值
3、细节问题,注意利用后序遍历时,注意控制最后一个根节点的位置
4、利用dfs,深度优先搜索时同样注意理解递归寻找的本质,注意递归结束的控制条件,二叉树的递归遍历,注意掌握三种遍历方式与dfs结合的运用,路径问题注意搜索方法的运用