Question: Enter the result of the forward and middle traversal of a binary tree. re-create the binary tree. Assume that the input results do not contain repeated numbers. Enter the pre-order traversal sequence {,} and the middle-order traversal sequence {,}. re-create a binary tree and output its header node.
Solution: In the forward traversal of a binary tree, the first number is always the value of the root node of the tree. However, in a sequential traversal sequence, the value of the root node is in the middle of the sequence, and the value of the node of the Left subtree is on the left of the value of the root node, the node value of the right subtree is located on the right of the value of the root node. Therefore, we need to scan the central sequence to find the value of the root node.
After finding the root node, the left side of the root node is the left subtree of the tree, and the right side is the right subtree of the tree, and then recursion.
C language source code:
# Include <stdio. h> # include <stdlib. h> struct node {int data; struct node * lchild; struct node * rchild;}; // re-build a binary tree struct node * construct (int * preorder, int * endpreorder, int * inorder, int * endinorder) {int * r; int leftlens; int * leftpreend; int rootvalue = preorder [0]; struct node * root = (struct node *) malloc (sizeof (struct node); root-> DATA = rootvalue; root-> lchild = NULL; root-> rchild = NULL; if (preord ER = endpreorder & inorder = endinorder & * preorder = * inorder) return root; r = inorder; while (* r! = Rootvalue & R <= endinorder) r ++; leftlens = r-inorder; leftpreend = preorder + leftlens; If (leftlens> 0) root-> lchild = construct (preorder + 1, leftpreend, inorder, R-1); If (leftlens <endpreorder-preorder) Root-> rchild = construct (leftpreend + 1, endpreorder, R + 1, endinorder); Return root;} // print the binary tree void houxu (struct node * root) {If (root = NULL) return; houxu (root-> lchild); houxu (root-> rchild); printf ("% d", root-> data);} int main () {int lens; int preorder [10]; int inorder [10]; int I; struct node * root; printf ("Enter the number of sequence elements: \ n "); scanf ("% d", & lens); printf ("Enter the preordered sequence"); for (I = 0; I <lens; I ++) scanf ("% d", & preorder [I]); printf ("Please input the central sequence"); for (I = 0; I <lens; I ++) scanf ("% d", & inorder [I]); root = construct (preorder, preorder + lens-1, inorder, inorder + lens-1); houxu (Root ); return 0 ;}
Rebuilding a binary tree