树的三种遍历

xiaoxiao2021-02-28  56

/* 7 2 3 1 5 7 6 4 1 2 3 4 5 6 7 * 4 1 6 3 5 7 2 */ #include<iostream> #include<cstring> #include<cstdlib> typedef struct node { struct node *left; struct node *right; int data; }Node; using namespace std; Node *binarytree(int a[],int b[],int len) { int i; if (len==0) return NULL; Node *tree; tree=(Node *)malloc(sizeof(Node)); tree->data=a[len-1]; for (i=0;i<len;i++) { if (b[i]==a[len-1]) break; } tree->left=binarytree(a,b,i); tree->right=binarytree(a+i,b+i+1,len-i-1); return tree; } void printtree(Node *head) { if (head==NULL) return ; else { //cout<<head->data<<" ";//前序 printtree(head->left); //cout<<head->data<<" ";//中序 printtree(head->right); //cout<<head->data<<" ";//后序 } } int main() { int n; cin>>n; int mid[n],next[n]; for (int i=0;i<n;i++) cin>>next[i]; for (int i=0;i<n;i++) cin>>mid[i]; Node *tree; tree=binarytree(next,mid,n); printtree(tree); }
转载请注明原文地址: https://www.6miu.com/read-2619092.html

最新回复(0)