UVA 548 - Tree
2017-09-03 17:59
302 查看
题目大意:给你二叉树的中序遍历,和后序遍历的结果。让你求,权值最小的叶子节点。也就是从根到叶子结点的值的和最小的点。如果权值相等,输出叶子节点值较小的点。
解题思路:由后序遍历得到根节点的值。即后序遍历最后一个为根,然后在中序遍历中查找这个根的值的位置,左边为左子树,右边为右子树。针对左子树也是同样操作,找“根”(左子树的全体作为树),根的左右子树。也就是递归求树。建树。这是第一题完全自己做得...刚开始以为是求最小叶子节点,后面根据写完的代码,改一下就有了树,所以这里我不会讲思路的。美滋滋。欢迎一起讨论
ac代码:
解题思路:由后序遍历得到根节点的值。即后序遍历最后一个为根,然后在中序遍历中查找这个根的值的位置,左边为左子树,右边为右子树。针对左子树也是同样操作,找“根”(左子树的全体作为树),根的左右子树。也就是递归求树。建树。这是第一题完全自己做得...刚开始以为是求最小叶子节点,后面根据写完的代码,改一下就有了树,所以这里我不会讲思路的。美滋滋。欢迎一起讨论
ac代码:
#include <iostream> #include <map> using namespace std; multimap <int, int>ma; map <int, int>::iterator it; int a[10005], b[10005], count; using namespace std; struct tree{ int data; int sum; tree *left; tree *right; tree() { data = sum = 0; left = right = NULL; } }; tree *ro; tree* dfs(int m, int n, int t, int k, tree* ro) { int root=b ; tree *node; node = new tree; node->data = root; node->sum = ro->sum + root; if (k-t == 1){ ma.insert(make_pair(node->sum, node->data)); return node; } for (int i=t; i<k; i++) if (a[i] == root){ node->left = dfs(m, m+i-t-1, t, i, node); node->right = dfs(m+i-t, n-1, i+1, k, node); break; } } int input(int a[]) { char c = getchar(); int i = 1; while (c != '\n'){ scanf("%d", &a[i++]); c = getchar(); } return i; } int main() { int i; char c; while (scanf("%d", &a[0])!=EOF){ ro = new tree; input(a); scanf("%d", &b[0]); count = input(b); dfs(0, count-1, 0, count, ro); it=ma.begin(); cout << it->second << endl; ma.clear(); } return 0; }
相关文章推荐
- UVA 548 Tree
- UVA_548: Tree
- Tree UVA - 548
- uva 548 Tree
- 【日常学习】【二叉树遍历】Uva548 - Tree题解
- uva548 tree
- UVA548——Tree(中后序建树+DFS)
- Uva548 Tree 【递归建树+dfs遍历树】【例题6-8】
- uva 548 - Tree
- uva 548 - Tree
- UVa 548 - Tree【二叉树的递归遍历(DFS)】
- UVA 548-Tree(二叉树)
- uva 548 - Tree
- UVa 548 Tree【二叉树的递归遍历】
- 【UVA 548 Tree】二叉树构造 & 遍历
- UVA 548 Tree
- uva 548 Tree
- UVA 548 Tree(中序+后序还原二叉树)
- UVA548- Tree
- Tree UVA - 548