uva 548 Tree
2013-10-06 23:51
363 查看
利用这道题目学习了利用前序和中序以及后序和中序序列来递归重构二叉树的方法,只要重构出二叉树,剩下的东西就好说了,也是递归处理,从根节点往下看,往左走还是往右走取决于左子树能够取到的最小路径总和值和右子树能取到的最小路径综合值的大小关系,自顶向下分析,自底向上运算来构造递归算法就行了,最后用先序遍历候选的叶子节点,选出最小的就行了。
#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_LEN 10005 int in[MAX_LEN]; int post[MAX_LEN]; int min; struct node { int value; int new_value; struct node *left; struct node *right; }; struct node* build_tree(int *inorder, int *postorder, int len) { if(len == 0) return NULL; int left_len, right_len; //左子树和右子树的节点个数 struct node *root, *left_son, *right_son; int i; root = (struct node*)malloc(sizeof(struct node)); root->value = postorder[len-1]; //后序的最后一个一定为根节点 //在中序序列中找到根节点位置 for(i=0; i<len; i++) if(inorder[i] == postorder[len-1]) break; left_len = i; right_len = len-left_len-1; left_son = build_tree(inorder, postorder, left_len); right_son = build_tree(inorder+i+1, postorder+left_len,right_len); root->left = left_son; root->right = right_son; return root; } void most_small(struct node *root) { if(root == NULL) return; if(root->left==NULL && root->right==NULL) { root->new_value = root->value; return; } most_small(root->left); most_small(root->right); if(root->left && root->right) { if(root->left->new_value < root->right->new_value) root->new_value = root->value + root->left->new_value; else root->new_value = root->value + root->right->new_value; } else if(root->left) { root->new_value = root->value + root->left->new_value; } else { root->new_value = root->value + root->right->new_value; } } //先序遍历 void pre_travel(struct node* root) { if(!root) return; if(root->left==NULL && root->right==NULL) { if(root->value < min) min = root->value; return; } if(root->left && root->new_value==root->left->new_value + root->value) pre_travel(root->left); if(root->right && root->new_value == root->right->new_value + root->value) pre_travel(root->right); } void delete_tree(struct node *root) { if(root == NULL) return; delete_tree(root->left); delete_tree(root->right); free((void*)root); } void func(struct node* root) { most_small(root); min = 20005; pre_travel(root); delete_tree(root); printf("%d\n", min); } int main(void) { //freopen("input.dat", "r", stdin); struct node *root; int res, num, count; int i; char ch; count = 0; while(1) { res = scanf("%d", &num); if(res == EOF) goto end; ch = getchar(); in[count++] = num; if(ch == '\n') { for(i=0; i<count; i++) scanf("%d", post+i); getchar(); root = build_tree(in, post, count); //利用中序和后序序列分别为in和post构建节点个数为strlen(in)的二叉树 func(root); count = 0; } } end: return 0; }
相关文章推荐
- uva-548 Tree
- uva 548 tree 树
- 【例题 6-8 UVA - 548】Tree
- Tree UVA - 548
- UVa 548 - Tree
- UVA548——Tree(中后序建树+DFS)
- uva 548 Tree
- UVa 548 - Tree(二叉树)
- UVa:548 Tree
- uva548 Tree
- Uva548 Tree
- UVA 548 Tree
- UVA 548 - Tree
- UVa 548 - Tree
- UVA - 548 Tree
- UVA 548 Tree 【树+DFS】
- uva 548 Tree
- UVa 548 Tree
- 算法入门经典二叉树DFS题目UVA548 Tree
- UVA 548 Tree(建树树的遍历)