数据结构

来源:互联网 发布:兄弟连it教育地址 编辑:程序博客网 时间:2024/05/21 18:52

数据结构


题目:给出二叉树的的中序和后序遍历,找一个叶子使得它到根的路径的权和最小,多解的话,叶子本身的权最小:
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-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;}
0 0
原创粉丝点击