Title: Rebuilding a binary tree
To enter the results of the pre-order traversal and the middle sequence traversal of a binary tree, rebuild the two-fork tree. It is assumed that both the pre-order traversal of the input and the results of the middle-order traversal do not contain Dong numbers. For example, enter the pre-sequence traversal sequence {1,2,4,7,3,5,6,8} and the middle sequence traversal sequence {4,7,2,1,5,3,8,6}, then rebuild the two fork tree as shown and output its head node.
The binary tree nodes are defined as follows:
struct Binarytreenode{int m_nvalue; Binarytreenode *m_pleft; Binarytreenode *m_pright;};
Create the root node. The first data of the pre-sequence traversal is the data of the root node, the position of the root node is found in the middle sequence traversal, and the pre-order and the sequence traversal sequences of the right subtree of the Saozi are respectively known.
Binarytreenode *rebuiltbitree (int *preorder,int *inorder, int treenum) {if (preorder==null| | inorder==null| | treenum<=0) {return NULL;} The first number of the pre-order traversal is the root node Binarytreenode *root=new binarytreenode;root->m_nvalue=preorder[0];root->m_pright=root- >m_pleft=null;//The root node is found in the middle sequence traversal, the left node of the root node is the left subtree, the right node is the right subtree int rootorder=-1;for (int i=0; i<treenum; i++) {if (root->m _nvalue==inorder[i]) {rootorder=i;break;}} if (rootorder==-1) {printf ("Invalid Input");} Rebuild left subtree int treenumleft=rootorder;int *preorderleft=preorder+1;int *inorderleft=inorder;root->m_pleft= Rebuiltbitree (preorderleft,inorderleft,treenumleft);//rebuild Right subtree int treenumright=treenum-treenumleft-1;int * Preorderright=preorder+treenumleft+1;int *inorderright=inorder+treenumleft+1;root->m_pright=rebuiltbitree ( Preorderright,inorderright,treenumright); return root;}
"Sword means offer" rebuilding binary tree