题意:输入一个二叉树的中序和后序,输出一个叶子节点,该叶子节点到根的数值总和最小。
分析:先通过后序和中序建立二叉树,在通过DFS进行搜索,找到符合题目要求的叶子节点。中序和后序建立二叉树:使用递归来建立,由后序确定当前递归中的分支的根节点,再在中序中找到根的位置,则中序中根左的为左子树的中序排列,根右的为右子树的中序。设此时左子树的长度为len,则当前的后序的前len个数据是左子树的后序排列。同理进行递归即可。右子树同理。
代码:
#include<stdio.h> #include<iostream> #include<string> #include<sstream> #include<algorithm> using namespace std; const int maxn=10010; int inorder[maxn]; //中序遍历数组 int postorder[maxn]; //后序遍历数组 int lch[maxn]; //二叉树左子树 int rch[maxn]; //二叉树右子树 int n; int best_sum,best; //最小权值和 最小节点编号 int read_list(int *a) { string line; if(!getline(cin,line)) return 0; stringstream ss(line); n=0; int x; while(ss>>x) a[n++]=x; return n>0; } int build(int l1,int r1,int l2,int r2) { if(l1>r1) // return 0; int root=postorder[r2]; //根节点 int p=l1; //根节点在中序的位置 while(inorder[p]!=root) p++; int cnt=p-l1; lch[root]=build(l1,p-1,l2,l2+cnt-1); //左子树 rch[root]=build(p+1,r1,l2+cnt,r2-1); //右子树 return root; } void dfs(int v,int sum) //dfs搜索 { sum+=v; if(!lch[v]&&!rch[v]) { if(sum<bestsum||(sum==best_sum&&v<best)) { best=v; bestsum=sum; } } if(lch[v]) dfs(lch[v],sum); if(rch[v]) dfs(rch[v],sum); } int main() { while(readlist(in_order)) //读入中序 { readlist(post_order); //后序 build(0,n-1,0,n-1); //建立二叉树 bestsum=0x3f3f3f3f; dfs(postorder[n-1],0); cout<<best<<"\n"; } }
UVA - 548 C - Tree
最新推荐文章于 2021-10-27 09:16:30 发布