给中序遍历和后续遍历,求从根到叶子权值最小的路径,的叶子节点的值。若有多条,求叶子最小的。
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
using namespace std;
const int maxn = 10005;
struct node{
int data;
node *lc,*rc;
node(int d) : data(d),lc(NULL),rc(NULL) {}
};
int in[maxn],post[maxn];
node* build(int *in,int *post,int n)
{
if(n == 0) return NULL;
int rt = post[n - 1];
node *root = new node(rt);
int p = 0;
while (p < n && in[p] != rt) {
p ++;
}
int l = p,r = n - p - 1;
if(l > 0)
root->lc = build(&in[0], &post[0], l);
if(r > 0)
root->rc = build(&in[p + 1], &post[p], r);
return root;
}
int minsum = 1 << 20,u = maxn;
//递归的时候,函数调用的栈其实就记录了在每个节点,从根至此的sum。
void dfs(node *cur,int sum)//sum为当前最小值
{
sum += cur->data;
if (cur->lc == NULL && cur->rc == NULL) {//为叶子节点
if (sum < minsum ||(sum == minsum && cur->data < u)) {
u = cur->data;
minsum = sum;
}
}
if (cur->lc != NULL) {
dfs(cur->lc, sum);
}
if(cur->rc != NULL)
{
dfs(cur->rc,sum);
}
}
int main()
{
string a;
while (getline(cin,a)) {
memset(in, 0, sizeof(in));
memset(post, 0, sizeof(post));
int sz = 0;
stringstream ss(a);
while (ss) {
ss >> in[sz ++];
}
ss.clear();ss.str("");//清空状态并赋为空串
getline(cin ,a);
sz = 0;
ss << a;
while (ss) {
ss >> post[sz ++];
}
node *root = build(in,post,sz - 1);
minsum = 1 << 20,u = maxn;
dfs(root, 0);
printf("%d\n",u);
}
return 0;
}