Construct a binary tree
Never
#include <stdlib.h> #include <stdio.h> typedef struct _node { int value; struct _node *left; struct _node *right; } Node; Node *create_node(int value){ Node *newnode = (Node*)malloc(sizeof(Node)); newnode->left = NULL; newnode->right = NULL; newnode->value = value; return newnode; } void postorder(Node *root){ if(root == NULL) return; postorder(root->left); postorder(root->right); printf("%d ",root->value); } void destroy(Node* root){ if(root == NULL)return; destroy(root->left); destroy(root->right); free(root); } /* Parameter description: int *inorder : the inorder traversal sequence of the binary tree. int *preorder : the preorder traversal sequence of the binary tree. int inorder_start : the starting index of the inorder traversal of the subtree. int inroder_end : the ending index of the inorder traversal of the subtree. As for the preorder traversal index, try declaring a static variable inside this function. */ Node *build(int *inorder, int *preorder, int inorder_start, int inorder_end){ static int preIndex = 0; if(inorder_start > inorder_end)return NULL; Node *node = create_node(preorder[preIndex++]); if(inorder_start == inorder_end) return node; int i; for(i=inorder_start;i<inorder_end;i++){ if(inorder[i] == node->value) break; } node->left = build(inorder,preorder,inorder_start,i-1); node->right = build(inorder,preorder,i+1,inorder_end); } int main(void){ int n; scanf("%d",&n); int *inorder = (int*)malloc(sizeof(int)*n); int *preorder = (int*)malloc(sizeof(int)*n); for(int i=0;i<n;i++){ scanf("%d",&inorder[i]); } for(int i=0;i<n;i++){ scanf("%d",&preorder[i]); } Node *root = build(inorder,preorder,0,n-1); postorder(root); printf("\n"); destroy(root); free(inorder); free(preorder); return 0; }
Raw Text
-
aswf0g98q0g9qw-g
2 min ago
-
grdfgbrg
23 min ago
-
zsxdvs
25 min ago
-
Korina Kova - OnlyFans Leaks
1 hour ago
-
dfsdfs fsfsd sfdd sdsffds
1 hour ago
-
Pedowoman boy
1 hour ago
-
C..P V.I.D..E.O.S
1 hour ago
-
πππ NEW CP UPDATE MAY 2024 VIDEOS WORKING ALL FREE FOLDER πππ
1 hour ago
-
CPπ LOL1ππ§ FOLDERSπ―π
1 hour ago
-
Untitled
1 hour ago