(遍历二叉树)HDU 1710 Binary Tree Traversals
2017-03-14 21:49
676 查看
查看原题
另外注意一下typedef * ->
题意
给出结点数,并给定先序遍历,中序遍历,求后序遍历思路
见代码另外注意一下typedef * ->
代码
#include <iostream> using namespace std; typedef struct node{ node *l,*r; int data; }*treenode; treenode create(int preorder[], int inorder[], int n,int root){ treenode temp; for(int i=0;i<n;i++){ if(inorder[i]==preorder[0]){ temp=(treenode)malloc(sizeof(node)); temp->data=inorder[i]; temp->l=create(preorder+1,inorder,i,root); temp->r=create(preorder+i+1,inorder+i+1,n-i-1,root); //递归函数中的建树过程其实也可以看作是一个后序遍历 if(temp->data!=root){ cout<<temp->data<<" "; } else{ cout<<temp->data<<endl; } return temp; } } return NULL; } int main(){ int n,preorder[1001],inorder[1001]; while(cin>>n){ for(int i=0;i<n;i++){ cin>>preorder[i]; } for(int i=0;i<n;i++){ cin>>inorder[i]; } treenode temp=create(preorder,inorder,n,preorder[0]); } return 0; }
//附上更好理解的代码 #include <iostream> #include <stack> using namespace std; typedef struct Node { Node *l,*r; //struct Node 与 Node 均可以 int num; }*tree; tree root; tree creat(int a[],int b[],int n) { tree ss; for (int i=0;i<n;i++) { if (a[0] == b[i]) { ss = (tree)malloc(sizeof(Node)); ss->num = b[i]; ss->l=creat(a+1,b,i); ss->r=creat(a+i+1,b+i+1,n-i-1); return ss; } } return NULL; } void post_order(tree h) { if (h !=NULL) //if判断一定不能少,因为到叶子的地方就停止了, { post_order(h->l); post_order(h->r); if (root == h) { cout<<h->num<<endl; } else cout<<h->num<<" "; } } int main() { int a[1000],b[1000],n,i; tree h; while (cin>>n) { for(i=0;i<n;i++) { cin>>a[i]; } for (i=0;i<n;i++) { cin>>b[i]; } root = h = creat(a,b,n); post_order(h); } return 0; }
相关文章推荐
- 【二叉树之遍历的应用】HDU 1710---Binary Tree Traversals
- 二叉树 遍历 hdu-1710-Binary Tree Traversals
- HDU 1710(Binary Tree Traversals)二叉树的遍历
- HDU 1710 Binary Tree Traversals 二叉树
- hdu 1710 Binary Tree Traversals (二叉树)
- HDU 1710 Binary Tree Traversals(二叉树)
- HDU 1710-Binary Tree Traversals(重建二叉树)
- 杭电1710 Binary Tree Traversals(二叉树的遍历)
- HDU1710 Binary Tree Traversals【树的遍历】
- hdu 1710 Binary Tree Traversals(二叉树排序)
- HDU 1710 - Binary Tree Traversals(树的遍历)
- hdu1710 Binary Tree Traversals ----- 二叉树前序中序推后序
- HDU 1710 Binary Tree Traversals(二叉树)
- HDU 1710 Binary Tree Traversals(二叉树)
- HDU 1710 Binary Tree Traversals(二叉树的后序遍历)
- hdoj 1710 Binary Tree Traversals(二叉树的建立及遍历)
- HDU1710——Binary Tree Traversals(二叉树)
- hdu_1710_Binary Tree Traversals(二叉树的重构)
- Binary Tree Traversals HDU - 1710 (二叉树求后序)
- 重建二叉树 Binary Tree Traversals HDU - 1710