UVa 548 Tree(建树+DFS)
题目链接
You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that path.
Input
The input file will contain a description of the binary tree given as the inorder and postorder traversal sequences of that tree. Your program will read two line (until end of file) from the input file. The first line will contain the sequence of values associated with an inorder traversal of the tree and the second line will contain the sequence of values associated with a postorder traversal of the tree. All values will be different, greater than zero and less than 10000. You may assume that no binary tree will have more than 10000 nodes or less than 1 node.
Output
For each tree description you should output the value of the leaf node of a path of least value. In the case of multiple paths of least value you should pick the one with the least value on the terminal node.
1.这种多文件的多行输入真的容易把人搞懵,书上的做法挺值得学习的。stringstream建议去自己学一下
2.另外就是如何去建树,书上写的是两个节点数组保存着左右孩子,传入根节点后DFS搜索。这样做的原理是本题中声明了每个节点的权值都不相同。笔者感觉还是按链表来写吧,这样更易懂更具广泛性,下文代码就是按链表来写的
3.DFS这个函数一定要搞懂,不能只知道原理却不知道如何去写函数。刚开始看不懂,想了一大会,sum是一个局部变量,在每次深搜到叶子时,从上一个非叶子节点的sum并没有变化,当返回搜右孩子时,又是一个新的权值和。这就是递归函数的奥妙所在。多思考多理解,以后DFS和BFS会很常用的,建议熟练掌握。
代码:
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
#define INF 0x7fffffff //刚开始记错了INF的值写成了0xffffffff-1,但这是-1,导致调试了好久
typedef struct BinaryTree{
int data;
struct BinaryTree *lchild,*rchild;
BinaryTree():data(0),lchild(nullptr),rchild(nullptr){}
}*BiNode;
BiNode newNode(){ return new BinaryTree(); } //不写该函数也可
const int maxn=1e4+10;
int in_order[maxn],post_order[maxn];
int num,cnt,res;
BiNode root;
bool read_line(int *a){
string s;
if(!getline(cin,s)) return false;
stringstream ss(s);
int x;
num=0;
while(ss>>x) a[++num]=x;
return num>0;
}
BiNode buildTree(int b1,int e1,int b2,int e2){
if(b1>e1) return nullptr;
BiNode r=newNode();
r->data=post_order[e2];
int k=b1;
while(in_order[k]!=r->data) k++;
int res=k-b1;
r->lchild=buildTree(b1,k-1,b2,b2+res-1);
r->rchild=buildTree(k+1,e1,b2+res,e2-1);
return r;
}
void DFS(BiNode T,int sum){
sum+=T->data;
if(!(T->lchild) && !(T->rchild)){
if(sum<res||(sum==res&&T->data<cnt)){
cnt=T->data;
res=sum;
}
}
if(T->lchild) DFS(T->lchild,sum);
if(T->rchild) DFS(T->rchild,sum);
}
/*void PreOrderTraverse(BiNode T) //先序遍历一下树
{
if(T==nullptr)
return;
printf("%d ",T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}*/
void freeMemory(BiNode T){
if(T==nullptr) return;
freeMemory(T->lchild);
freeMemory(T->rchild);
delete T;
}
int main()
{
while(read_line(in_order)){
read_line(post_order);
//每次循环后一定别忘了对全局变量的处理,一些赋值或者清0都得再来
res=INF;
root=buildTree(1,num,1,num);
//PreOrderTraverse(root);
DFS(root,0);
printf("%d\n",cnt);
freeMemory(root);
}
return 0;
}