HDU 1710 二叉树的遍历

#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;}elsecout<<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 二叉树的遍历

相关文章:

你感兴趣的文章:

标签云: