二叉树--uva548Tree 二叉树递归遍历
来源:互联网 发布:练字钢笔推荐 知乎 编辑:程序博客网 时间:2024/05/15 02:09
题目:uva548
分析:还能说什么,直接看懂了刘大爷的代码然后自己敲一遍啊。
ps:自己写的build_tree函数果然没有刘大爷的简洁,醉了。
而且啊,自己用cin.get()写的输入函数也没有刘大爷的stringstream好用啊。
#include <cstdio>#include <cstdlib>#include <iostream>#include <sstream>using namespace std;const int maxn = 10005;int in_order[maxn],post_order[maxn];int l[maxn],r[maxn];int n,ans,best_sum;bool read_line(int *a){string line; if(!getline(cin,line)) return false; stringstream ss(line); n = 0; int x; while(ss >> x) a[n++] = x;return n>0;}int build_tree(int in_b,int in_e,int po_b,int po_e){int root = post_order[po_e];int i = 0;while(in_order[in_b+i] != root) i++;//对于下面4句,刘大爷一句 if(in_b>in_e) return 0;就解决了,跪服if(i>0) l[root] = build_tree(in_b,in_b+i-1,po_b,po_b+i-1);else l[root] = 0; //调试的时候忘了写这一句,l数组也没有初始化,然后就。。一直崩溃if(in_b+i < in_e) r[root] = build_tree(in_b+i+1,in_e,po_b+i,po_e-1);else r[root] = 0;return root;}void dfs(int u,int sum){sum += u;if(!l[u] && !r[u]){if(sum < best_sum || (sum == best_sum && u < ans)){ans = u;best_sum = sum;}}if(l[u]) dfs(l[u],sum);if(r[u]) dfs(r[u],sum);} int main(){while(read_line(in_order)) {read_line(post_order); best_sum = 1e9; build_tree(0,n-1,0,n-1);//建树没问题 dfs(post_order[n-1],0); cout << ans << endl;}return 0;}参考:刘大爷紫书第六章第三节
阅读全文
0 0
- 二叉树--uva548Tree 二叉树递归遍历
- 二叉树递归遍历
- 二叉树遍历(递归)
- 二叉树递归遍历
- 递归遍历二叉树
- 递归二叉树遍历
- 二叉树递归遍历
- 递归遍历二叉树
- 二叉树递归遍历
- 二叉树--uva839 二叉树递归遍历
- 二叉树--uva699 二叉树递归遍历
- 二叉树的递归遍历
- 非递归遍历二叉树
- 二叉树遍历非递归
- 后序非递归遍历二叉树
- 非递归遍历二叉树
- 二叉树非递归遍历
- 二叉树非递归遍历
- 实现左旋函数的几种方法
- 百度编辑器过滤div标签问题
- opencv中人脸识别算法的基本原理
- 吉大路由器
- Spring Cloud 入门
- 二叉树--uva548Tree 二叉树递归遍历
- execute、executeQuery和executeUpdate之间的区别
- JS文字打字机效果
- 【Android】View测量的三种模式
- 列表和解释
- 最近配置django遇到了神奇的现象
- [BZOJ]1814 Ural 1519 Formula 1 插头DP
- Spring Boot 入门
- 原生JS添加Class/删除Class/判断Class