还原二叉树

来源:互联网 发布:电子商务降低成本数据 编辑:程序博客网 时间:2024/05/21 11:36

对于二叉树T,可以递归定义它的先序遍历、 中序遍历和后序遍历,如下所示:
PreOrder(T)=T的根结点+PreOrder(T的左子树)+PreOrder(T的右子树)
InOrder(T)=InOrder(T的左子树)+T的根结点+InOrder(T的右子树)
PostOrder(T)=PostOrder(T的左子树)+PostOrder(T的右子树)+T的根结点

若已知中序遍历和另一种遍历就能还原出二叉树

1.已知先序遍历和中序遍历:

a.先序遍历的第一个数是根节点;

b.中序遍历根节点左边是左子树,右边是右子树。

#include<stdio.h>#include<stdlib.h>#define MaxN 51typedef struct TreeNode BinTree;struct TreeNode{int data;BinTree *left;BinTree *right;};BinTree *CreatBinTree(char *pre,char *in,int len){BinTree *T;int i;if(! len)return NULL;T = (BinTree*)malloc(sizeof(BinTree));T->data = pre[0];for(i = 0;i < len;i ++)if(pre[0] == in[i])break;T->left = CreatBinTree(pre + 1,in,i);T->right = CreatBinTree(pre + i + 1,in + i + 1,len -i - 1);return T;}int Height(BinTree *T){int THeight,LHeight,RHeight;if(! T)THeight = 0;else{LHeight = Height(T->left);RHeight = Height(T->right);THeight = (LHeight > RHeight) ? LHeight : RHeight;THeight ++;}return THeight;}int main(){int N;char pre[MaxN],in[MaxN];BinTree *T = NULL;scanf("%d",&N);scanf("%s\n%s",pre,in);T = CreatBinTree(pre,in,N);printf("%d\n",Height(T));return 0;}

2.已知中序遍历和后序遍历

a.后序遍历的最后一个值是根节点
b.中序遍历根节点前面的数是左子树,有n个
c.后序遍历前n个数是左子树

题目:给一棵点带权(权值各不相同,都是小于10000的正整数)的二叉树的中序和后序遍历,找一个叶子使得它到根的路径上的权和最小。 如果有多解,该叶子本身的权应尽量小。输入中每两行表示一棵树,其中第一行为中序遍历,第二行为后序遍历。
样例输入:
3 2 1 4 5 7 6
3 1 2 5 6 7 47 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
255
255
样例输出:
1 3 2
55

#include<iostream>#include<string>#include<sstream>#include<algorithm>using namespace std;const int maxv = 10000 + 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);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 = L1;while(in_order[p] != root) p++;int cnt = p - L1;lch[root] = build(L1,p-1,L2,L2+cnt-1);rch[root] = build(p+1,R1,L2+cnt,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 = 1000000000;dfs(post_order[n-1],0);cout << best << "\n";}return 0;}

更详细参考http://www.cnblogs.com/lzjsky/archive/2011/01/04/1925538.html

stringstream ss_stream;
ss_stream << i; // 将int输入流中
ss_stream >> str; // 将ss_stream中的数值输出到str中

//注意:如果做多次数据转换;必须调用clear()来设置转换模式
ss_stream << "456";
ss_stream >> i; // 首先将字符串转换为int
ss_stream.clear();
ss_stream << true;
ss_stream >> i; // 然后将bool型转换为int;假如之前没有做clear,那么i会出错

//运行clear的结果
i = 456
i = 1
//没有运行clear的结果
i = 456
i = 8800090900


0 0
原创粉丝点击