题目

输入1
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
输入2
3 2 1 4 5 7 6
3 1 2 5 6 7 4
思路
和前面的还原二叉树一样
然后遍历第一个符合的路径即可
代码
#include<iostream>
#include<stack>
#include<sstream>
using namespace std;
int min_road = 9999999;
int min_leaf = 9999999;
struct dot
{
int data = -1;
dot* lchild = NULL;
dot* rchild = NULL;
void med_print()
{
if(!this)
return;
else
{
this->lchild->med_print();
cout << this->data << " ";
this->rchild->med_print();
}
}
};
void create_tree(dot* &root, int* med, int* post, int n)
{
if(n == 0)
root = NULL;
else
{
int root_loc = 0;
while(post[n - 1] != med[root_loc])
root_loc++;
root = new dot;
root->data = med[root_loc];
create_tree(root->lchild, med, post, root_loc);
create_tree(root->rchild, med + root_loc + 1, post + root_loc, n - root_loc - 1);
}
}
void min(dot*& root, int road = 0, int leaf = 0)
{
if(road > min_road)
{
return;
}
else if(!root)
{
if(road < min_road)
{
min_road = road;
min_leaf = leaf;
}
else if(road == min_road)
{
if(leaf < min_leaf)
min_leaf = leaf;
}
}
else
{
if(!root->lchild && !root->rchild)
{
min(root->lchild,road + root->data, root->data);
}
if(root->lchild)
min(root->lchild,road + root->data, root->data);
if(root->rchild)
min(root->rchild,road + root->data, root->data);
}
}
int main()
{
string str;
getline(cin,str);
stringstream sin(str);
int med[10000] = {0};
int post[10000] = {0};
int n = 0;
while(sin >> med[n++]){}
getline(cin,str);
sin.clear();
sin.str(str);
n = 0;
while(sin >> post[n++]){}
n--;
// for(int i = 0; i < n ; i++)
// cout << med[i] <<" " << post[i] << endl;
dot* root; create_tree(root, med, post, n);
min(root);
cout << min_leaf << endl;
}
这篇博客介绍了如何根据中序和后序遍历数组构建二叉树,并找到从根节点到叶子节点的最小路径。通过递归算法实现树的创建,然后遍历寻找最小路径,代码使用C++编写。
1027

被折叠的 条评论
为什么被折叠?



