Problem:
Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Hide TagsTree Array Depth-first SearchTest instructions: Constructing a two-fork tree by using the binary tree's pre-sequence traversal sequence and the middle sequence traversal sequence, a classic problem
Thinking:
(1) The order of the pre-order traversal is: parent node, left child, right child, the order of the sequence traversal is: Left child, parent node, right child
(2) The first element of the pre-sequence traversal sequence is the parent node, the position of the node can be found in the sequential traversal sequence, the number of nodes of the Zuozi is calculated using the difference of the position, and the number of right subtree nodes is known. After the parent node is removed from the sequence traversal sequences, the first element is the left child of the parent node, and the first node of the right subtree of the pre-sequence traversal sequence is the parent node's right child
(3) According to the above thought recursion, can construct two fork tree
(4) since the parameter type of the make () function is vector<int>::iterator, it is too long, and the template function is used here to simplify.
Code
Class Solution {public: TreeNode *buildtree (vector<int> &preorder, vector<int> &inorder) { if (preorder.size () ==0 | | inorder.size () ==0) return NULL; if (Preorder.size ()!=inorder.size ()) return NULL; Return make (Preorder.begin (), Preorder.end (), Inorder.begin (), Inorder.end ()); } Private: template<class it> TreeNode *make (it pfirst,it plast,it qfirst,it qlast) { if (pfirst ==plast) return NULL; if (qfirst==qlast) return NULL; int A=*pfirst; TreeNode *node= New TreeNode (a); It Loc=find (qfirst,qlast,a); int left_size = Loc-qfirst; Node->left=make (pfirst+1,pfirst+left_size+1,qfirst,loc); Node->right=make (pfirst+left_size+1,plast,loc+1,qlast); return node; }};
Leetcode | | 105, Construct Binary Tree from preorder and inorder traversal