二叉树建树
来源:互联网 发布:期刊软件 编辑:程序博客网 时间:2024/06/10 13:47
给出前序和中序建树:
Node* build (int n, int* pre, int* in) { Node* node = new Node; int i = 0; if (n <= 0) return NULL; while (in[i] != pre[0]) i++; node -> val = in[i]; node -> left = build(i, pre + 1, in); node -> right = build(n - i - 1, pre + i + 1, in + i + 1); return node;}
给出中序和后序建树:
Node* build (int n, int* in, int* pos) { Node* node = new Node; int i = n - 1; if (n <= 0) return NULL; while (in[i] != pos[n - 1]) i--; node -> val = ino[i]; node -> left = build(i, in, pos); node -> right = build(n - i - 1, in + i + 1, pos + i); return node;}
UVA-548 给你一棵树的中序和后序遍历,求从根到叶子组成的路径中数字和最小的那条,输出最小路径的叶子。
思路:在重建完二叉树后,dfs遍历找到最小路径和叶子
#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <algorithm>using namespace std;int in[10010],pos[10010];int min1,ans;struct tree{ int data; tree *l,*r;};tree *root;tree* build(int n, int* in, int* pos){ tree* node = new tree; int i=n-1; if (n<=0) return NULL; while (in[i]!=pos[n-1]) i--; node->data=in[i]; node->l=build(i,in, pos); node->r=build(n-i-1,in+i+1,pos+i); return node;}void dfs(tree *tr,int sum){ if(tr==NULL) { return; } sum=sum+tr->data; if(tr->l==NULL&&tr->r==NULL) { if(min1>sum) { ans=tr->data; min1=sum; } } else { if(tr->l!=NULL) { dfs(tr->l,sum); } if(tr->r!=NULL) { dfs(tr->r,sum); } }}int main(){ char ch; while(scanf("%d%c",&in[0],&ch)!=EOF) { int n=1; for(int i=1;ch!='\n';i++) { scanf("%d%c",&in[i],&ch); n++; } ch = ' '; for(int i=0;ch!='\n';i++) { scanf("%d%c",&pos[i],&ch); } min1=1000001; root=build(n,in,pos); dfs(root,0); printf("%d\n",ans); } return 0;}
杭电1710
根据前序遍历和中序遍历,输出后序遍历
#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>using namespace std;const int N=1010;int pre[N],in[N];struct tree{ int data; tree *l,*r;};tree *root;tree *Creattree(int *pre,int *in,int n){ tree *tem; for(int i=0;i<n;i++) { if(pre[0]==in[i]) { tem=(tree*)malloc(sizeof(tree)); tem->data=in[i]; tem->l=Creattree(pre+1,in,i); tem->r=Creattree(pre+i+1,in+i+1,n-(i+1)); return tem; } } return NULL;}void Printfpos(tree *rt){ if(rt!=NULL) { Printfpos(rt->l); Printfpos(rt->r); if(rt==root) { printf("%d\n",rt->data); } else { printf("%d ",rt->data); } }}int main(){ int n; while(scanf("%d",&n)!=EOF) { for(int i=0;i<n;i++) { scanf("%d",&pre[i]); } for(int i=0;i<n;i++) { scanf("%d",&in[i]); } root=Creattree(pre,in,n); Printfpos(root); } return 0;}
阅读全文
0 0
- 二叉树层次建树.
- 二叉树建树
- 二叉树建树
- 二叉树非递归建树
- 二叉树的建树方法
- BST 二叉搜索树 (动态建树与静态建树)
- hdu5444 Elven Postman 二叉树建树
- HDU 5444-二叉树的遍历+建树
- UVA 548Tree(二叉树建树)
- 二叉树.u122给坐标建树
- 二叉树——不建树遍历
- 数据结构——二叉树的建立和遍历(递归建树&层序遍历建树)
- sdibt 2734 树与二叉树 (模拟建树)
- UVA 11234 - Expressions 二叉树建树+BFS 层次遍历
- UVA 699(二叉树建树与遍历)
- JD 1009:二叉搜索树(静态数组建树)
- BST二叉搜索树的建树和先序遍历
- sdibt 2746 二叉树的输入 (先序建树)
- 源码(一)
- 时间类的使用
- 【递归入门】组合+判断素数
- udp_send
- linux
- 二叉树建树
- Data structure-6 红黑树(BlackRedTree)插入操作
- Runloop
- Excel 技巧百例:汉字列的合并
- 提高数据库效率的方法
- 堆和栈的区别
- HDU6034 Balala Power!【贪心】
- java设计模式之五:代理模式
- Leetcode OJ 125 Valid Palindrome [Easy]