数据结构
2016-06-06 11:18
246 查看
数据结构
题目:给出二叉树的的中序和后序遍历,找一个叶子使得它到根的路径的权和最小,多解的话,叶子本身的权最小:3 2 1 4 5 7 6
3 1 2 5 6 7 4
1
先根据先序和后序的关系求一个完整的树,然后用深度递归来计算。
代码如下:
//题解,用中序和后序建立一棵树 //通过遍历这个数求出最优解 #include "stdafx.h" #include <string> #include <algorithm> #include <sstream> //字符串流 #include <iostream> //输入输出流 using namespace std; const int maxv = 1000 + 10; int in_order[maxv], post_order[maxv], lch[maxv], rch[maxv]; int n; bool read_list(int *a) { string line; if (!getline(cin, line)) return false; stringstream ss(line); //stringstream 头文件是sstream读入的是line,这里用到sstringstream的用法 n = 0; int x; while (ss >> x) a[n++] = x; 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 = 0,ch; while (in_order[p] != root) p++; ch = p - L1;//左子树节点个数 //用数组实现树结构 lch[root] = build(L1, p - 1, L2, L2 + ch - 1); rch[root] = build(p + 1, R1, L2 + ch, R2- 4000 1); return root; } int best, best_sum; void dfs(int u, int 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() { while (read_list(in_order)) { read_list(post_order); build(0, n - 1, 0, n - 1); best_sum = 100000; dfs(post_order[n - 1], 0); cout << best << endl; cout << best_sum << endl; } return 0; }
相关文章推荐
- 4.数据结构--线性表之静态链表
- 数据结构与算法-桶排序
- 基数树(radix tree)
- 【数据结构】链表的原理及与其相关的常见面试题总结
- 数据结构之二叉树
- 数据结构之二叉树
- 数据结构之二叉树
- HashMap HashTable HashSet区别剖析总结
- [数据结构与算法分析]栈的应用-学习笔记
- Binary Indexed Tree(二进制索引树、树状数组)
- 数据结构自学之路---单链表
- 数据结构之数组
- 数据结构之数组
- 数据结构之数组
- 线性表--链式描述(一)
- 数据结构之2-3-4树
- 数据结构之2-3-4树
- 数据结构之2-3-4树
- redis数据结构之dict 概要
- 常用树类数据结构总结-二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)的性能分析