博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Tree(树的还原以及树的dfs遍历)
阅读量:6984 次
发布时间:2019-06-27

本文共 2081 字,大约阅读时间需要 6 分钟。

紫书:P155 

uva  548

 

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.

 

 

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.

 

 

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.

 

 

 

3 2 1 4 5 7 63 1 2 5 6 7 47 8 11 3 5 16 12 188 3 11 7 16 18 12 5255255

 

 

 

13255

 

 给出一棵树的后序和中序遍历结果,要求求出从某个叶子节点回到树根的最小叶子节点,注意这是一颗带权树

后序遍历的最后一个节点是树根,而中序遍历的树根在中间,而且其左边全都是左子树子孙,右边是右子树子孙。

那么可以这样做:

1.从后序遍历中取出根

2.在中序遍历中找到根的位置,并以此位置把序列分为左子树和右子树

3.递归地对左子树和右子树执行1,2操作

 

#include 
#include
using namespace std;const int maxsize=1e4+10;int In_order[maxsize],Post_order[maxsize],lchild[maxsize],rchild[maxsize];int Shortest_path;int Shortest_path_node;int n;bool input(int *a){ string line; if(!getline(cin,line)) return false; n=0; stringstream ss(line); while(ss>>a[n]) n++; return n>0;}int Build(int L1,int R1,int L2,int R2){ if(L1>R1) return 0; int root=Post_order[R2]; int p=L1; while(In_order[p]!=root) p++; int cnt=p-L1; lchild[root]=Build(L1,p-1,L2,L2+cnt-1); rchild[root]=Build(p+1,R1,L2+cnt,R2-1); return root;}void dfs(int u,int sum){ sum+=u; if(!lchild[u]&&!rchild[u]) { if(sum
View Code

 

转载于:https://www.cnblogs.com/zsyacm666666/p/5002760.html

你可能感兴趣的文章
【poi xlsx报错】使用POI创建xlsx无法打开
查看>>
UNIX环境高级编程笔记之文件I/O
查看>>
DIV+CSS规范命名
查看>>
我的2013 Q.E.D
查看>>
2017 Multi-University Training Contest - Team 9 1002&&HDU 6162 Ch’s gift【树链部分+线段树】...
查看>>
4.5. Rspamd
查看>>
ArcMap中的名称冲突问题
查看>>
(转) 一张图解AlphaGo原理及弱点
查看>>
美联邦调查局 FBI 网站被黑,数千特工信息泄露
查看>>
掉电引起的ORA-1172错误解决过程(二)
查看>>
在网站建设过程中主要在哪几个方面为后期的网站优打好根基?
查看>>
【MOS】RAC 环境中最常见的 5 个数据库和/或实例性能问题 (文档 ID 1602076.1)
查看>>
新年图书整理和相关的产品
查看>>
Struts2的核心文件
查看>>
Spring Boot集成Jasypt安全框架
查看>>
GIS基础软件及操作(十)
查看>>
HDOJ 2041 超级楼梯
查看>>
1108File Space Bitmap Block损坏能修复吗2
查看>>
遭遇DBD::mysql::dr::imp_data_size unexpectedly
查看>>
人人都会设计模式:03-策略模式--Strategy
查看>>