Title: Construct a tree from the pre-order and middle-sequence traversal results of a tree.
The first node of the result of the pre-order traversal is the root of the tree, and in the middle-order traversal results, the left side of the root node is the tree, and the right side is the tree's rightmost subtree. Then we re-determine the range of the right subtree of the Saozi and recursively look for the root node of the Saozi right subtree.
treenode* Buildsubtree (vector<int>& preorder,vector<int>& Inorder,intPre_start,intPre_end,intIn_start,intin_end) { if(pre_start>pre_end)returnNULL; TreeNode* root=NewTreeNode (Preorder[pre_start]); intI=In_start; while(i<=in_end&&inorder[i]!=Preorder[pre_start]) I++; intpos=i; intleftlength=pos-In_start; Root->left=buildsubtree (preorder,inorder,pre_start+1, pre_start+leftlength,in_start,pos-1); Root->right=buildsubtree (preorder,inorder,pre_start+leftlength+1, pre_end,pos+1, In_end); returnRoot; } TreeNode* Buildtree (vector<int>& Preorder, vector<int>&inorder) { if(preorder.size () = =0|| Inorder.size () = =0) returnNULL; returnBuildsubtree (Preorder,inorder,0, Preorder.size ()-1,0, Inorder.size ()-1); }
The point to note here is the recursive termination condition: pre_start>pre_end.
Construct Binary Tree from preorder and inorder traversal