#include <bits/stdc++.h>
using namespace std;
typedef struct BiNODE
{
int data;
BiNODE* lchild;
BiNODE* rchild;
}BiNODE;
BiNODE* recursiveBuilTree_post(BiNODE* root, int* post_s, int* mid_s, int post_low, int post_high, int mid_low, int mid_high)
{
BiNODE* root_2;
root_2 = new(BiNODE);
if (mid_high < mid_low)
return nullptr;
if (mid_high == mid_low)
{
root_2->data = mid_s[mid_low];
root_2->lchild = nullptr;
root_2->rchild = nullptr;
return root_2;
}
else
{
int i = post_high, j = mid_low;
while (i >= post_low)
{
bool flag = false;
for (j = mid_low; j <= mid_high; j++)
{
if (post_s[i] == mid_s[j])
{
flag = true;
break;
}
}
if (flag == true)
break;
i--;
}
root_2->data = post_s[i];
if (j == mid_low)
{
root_2->lchild = nullptr;
root_2->rchild = recursiveBuilTree_post(root_2, post_s, mid_s, post_low, i - 1, j + 1, mid_high);
}
else if (j == mid_high)
{
root_2->lchild = recursiveBuilTree_post(root_2, post_s, mid_s, post_low, i - 1, mid_low, j - 1);
root_2->rchild = nullptr;
}
else
{
root_2->lchild = recursiveBuilTree_post(root_2, post_s, mid_s, post_low, i - 1, mid_low, j - 1);
root_2->rchild = recursiveBuilTree_post(root_2, post_s, mid_s, post_low, i - 1, j + 1, mid_high);
}
return root_2;
}
}
BiNODE* buildTree_post_in()//后序+中序建树
{
vector<int> v;
int tmp=0;
while(cin >> tmp){
v.push_back(tmp);
}
int cnt = v.size()/2;
int num_in;
int post_s[cnt], mid_s[cnt];
for (int i = 0; i < cnt; i++)
{
mid_s[i] = v[i];
}
for (int i = 0; i < cnt; i++)
{
post_s[i] = v[i+cnt];
}
int root_data = post_s[cnt - 1];
int i = 0;
while (mid_s[i] != root_data)
i++;
BiNODE* root = new(BiNODE);
root->data = root_data;
root->lchild = recursiveBuilTree_post(root, post_s, mid_s, 1, cnt - 1, 0, i - 1);
root->rchild = recursiveBuilTree_post(root, post_s, mid_s, 1, cnt - 1, i + 1, cnt - 1);
return root;
}
typedef struct node
{
int data;
int sum;
}node;
vector<node> v;
void get(BiNODE* root, node now)
{
now.data = root->data;
now.sum += root->data;
if(!root->lchild && !root->rchild){
v.push_back(now);
return;
}
if(root->lchild){
get(root->lchild, now);
}
if(root->rchild){
get(root->rchild, now);
}
}
bool cmp(node a, node b)
{
if(a.sum < b.sum) return true;
else if(a.sum == b.sum){
if(a.data < b.data) return true;
else return false;
}
else return false;
}
int main()
{
BiNODE* root = buildTree_post_in();
node* tmp = new node();
tmp->data = 0;
tmp->sum = 0;
get(root, *tmp);
sort(v.begin(), v.end(), cmp);
cout << v[0].data << endl;
return 0;
}
EOJ_1068_最小权值路径
最新推荐文章于 2022-02-15 22:16:52 发布
该博客介绍了一种使用递归方法,通过后序遍历(post-order)和中序遍历(in-order)构建二叉树的算法。它首先定义了一个BiNODE结构,并实现了`recursiveBuilTree_post`函数来根据给定的序列构建二叉树。`buildTree_post_in`函数则用于实际的构建过程,从用户输入中读取序列并调用后序遍历构建函数。最后展示了如何遍历并排序构建好的二叉树。
摘要由CSDN通过智能技术生成