二叉树的递归遍历 Tree UVa548

时间:2023-03-09 18:21:05
二叉树的递归遍历 Tree UVa548

二叉树的递归遍历 Tree UVa548

题意:给一棵点带权的二叉树的中序和后序遍历,找一个叶子使得他到根的路径上的权值的和最小,如果多解,那该叶子本身的权值应该最小

解题思路:1.用getline()输入整行字符,然后用stringstream获得字符串中的数字                                                              2.用数组in_oder[]和post_order[]分别表示中序遍历和后序遍历的顺序,用数组rch[]和lch[]分别表示结点的左子树和右子树                                            3.用递归的办法根据遍历的结果还原二叉树(后序遍历的最后一个树表示的是根节点,中序遍历的中间一个表示根节点)                                             4.二叉树构造完成后,再执行一次递归遍历找出最优解

代码如下:

 #include<stdio.h>       //用数组存储二叉树
#include<string>
#include<sstream>
#include<iostream>
using namespace std;
const int MAXX=;
int in_order[MAXX],post_order[MAXX],lch[MAXX],rch[MAXX];
int n; bool read_list(int *a){
string line ;
if(!getline(cin,line)) return false;
stringstream ss(line);
n=;
int x;
while(ss>>x) a[n++]=x;
return n>;
} //把in_order[L1...R1]和post_order[L2...R2]建成一棵树,返回树根
//递归建立二叉树,数组存储左右结点
int build(int L1,int R1,int L2,int R2){
if(L1>R1) return ;
int root=post_order[R2];
int p=L1;
while(in_order[p]!=root)p++;
int cnt=p-L1;//左子树的结点树
lch[root]=build(L1,p-,L2,L2+cnt-);
rch[root]=build(p+,R1,L2+cnt,R2-);
return root;
} int best,best_sum;//目前对应的最优解和权值的和 void dfs(int u,int sum){
sum=sum+u;
if(!lch[u]&&!rch[u]){
if(sum<best_sum||(sum==best_sum&&u<best)){
best=u;
best_sum=sum;
}
}
if(lch[u]) dfs(lch[u],sum);
if(rch[u]) dfs(rch[u],sum);
} int main(){
freopen("in.txt","r",stdin);
while(read_list(in_order)){
read_list(post_order);
build(,n-,,n-);
best_sum=1e9;
dfs(post_order[n-],);
printf("%d\n",best);
}
}

此题中二叉树的应用,比如用中序遍历和后序遍历构造出原来的二叉树,还有递归的遍历二叉树,以没有子树为递归跳出的条件