UVA 548 —— 二叉树的递归遍历
来源:互联网 发布:js字符串包含某个字符 编辑:程序博客网 时间:2024/05/17 10:25
已知二叉树的中序遍历和后序遍历,构建二叉树,求叶子到根的最小路径权值和;
后序遍历的最后一个字符即为二叉树的根结点,然后在中序遍历中找到这个根结点的位置,根结点的左边序列即为该根的左子树,右边序列即为右子树,然后再在后序遍历中找左右子树的根结点,以此类推,用递归遍历。
#include<bits/stdc++.h>#define INF 0x3f3f3f3fusing namespace std;const int maxn = 1e4+5;int in_order[maxn], post_order[maxn];int lch[maxn], rch[maxn];int cnt;bool read_input(int* a){ cnt = 0; string s; if(!getline(cin, s)) return false; int len = (int)s.size(); int tmp = 0; for(int i = 0;i<len;i++){ if(s[i] == ' '){ a[cnt++] = tmp; tmp = 0; continue; } tmp = tmp*10+(s[i]-'0'); } a[cnt++] = tmp; if(cnt > 0) return true; else return false;}int build(int L1, int R1, int L2, int R2){ if(L1 > R1) return 0; //空树 int root = post_order[R2]; int i; for(i = L1;i<=R1;i++){ if(in_order[i] == root) break; } int k = i-L1; lch[root] = build(L1, i-1, L2, L2+k-1); rch[root] = build(i+1, R1, L2+k, R2-1); return root;}int ans, tmp;void dfs(int u, int sum){ if(u == 0) return; sum += u; if(!lch[u] && !rch[u]){ //叶子 if(ans > sum || (ans == sum && tmp > u)){ ans = sum; tmp = u; } return; } dfs(lch[u], sum); dfs(rch[u], sum);}int main(){ while(read_input(in_order)){ read_input(post_order); build(0, cnt-1, 0, cnt-1); ans = INF; dfs(post_order[cnt-1], 0); cout<<tmp<<endl; } return 0;}
0 0
- UVA 548 —— 二叉树的递归遍历
- UVa 548 - Tree【二叉树的递归遍历(DFS)】
- UVa 548(二叉树的递归遍历、dfs)
- 二叉树的遍历——递归和非递归
- 遍历二叉树——递归遍历
- Uva 248 Tree//二叉树遍历,递归
- 树——二叉树的遍历之递归实现
- 二叉树(2)——遍历的非递归实现
- 二叉树的非递归遍历——java实现
- 数据结构例程——二叉树遍历的递归算法
- 项目二——二叉树遍历的递归思想
- 数据结构实践—— 二叉树遍历的递归算法
- 数据结构—二叉树的遍历—递归
- 二叉树的非递归遍历——前序
- 二叉树的基本实现和遍历——递归
- 第九周——二叉树遍历的递归算法
- 二叉树的递归遍历
- 二叉树的递归遍历
- ARM汇编中ldr伪指令和ldr指令
- 数据结构C——单链表
- 文章标题
- 解决小米手机不能运行Android Studio程序的问题
- 从Android源码的角度理解应用开发(2)-Focus机制
- UVA 548 —— 二叉树的递归遍历
- 深入理解javascript函数定义与函数作用域
- 升级gradle版本之后小米手机调试安装失败
- Spring(五、AOP面向切面编程)
- PAT算法笔记(十六)————组个最小数
- SBULL块设备驱动程序分析
- 休闲时光的小代码-----用div格式制作田字格
- JavaScript 异步机制
- 查看过程函数包含内容