Title Description:
Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Problem solving: The first element of the first order traversal is the root element, and the position of the root element is found in the middle sequence traversal sequence. The middle sequence traverses the root element to the left of the record sequence, and to the right is the sequential traversal sequence of the right sub-tree. According to the length of sequence traversal sequences in the left and right sub-tree, the first sequence traversal sequence can be divided into two parts, the first sequence traversal sequence of Zuozi on the left, and the first sequence traversal sequence of the starboard tree on the right. The first order sequence and sequence of the left and right subtree are known, and the result can be obtained by invoking the above method recursively on the left and the sub-tree.
Code:
TreeNode * Build_tree (Vector<int>::iterator prel,vector<int>::iterator prer,vector<int>:: Iterator inl,vector<int>::iterator INR) { if (prel >= prer) return NULL; TreeNode * ROOT; if (Prer-prel = = 1) { root = new TreeNode (0); Root->val = *prel; return root; } root = new TreeNode (0); Root->val = *prel; Vector<int>::iterator Root_pos = Find (inl,inr,root->val); int left_length = ROOT_POS-INL; Root->left = Build_tree (prel+1,prel+1+left_length,inl,inl+left_length); Root->right = Build_tree (PREL+1+LEFT_LENGTH,PRER,INL+LEFT_LENGTH+1,INR); return root;} TreeNode * Solution::buildtree (vector<int> &preorder, vector<int> &inorder) { return build_ Tree (Preorder.begin (), Preorder.end (), Inorder.begin (), Inorder.end ());
Leetcode:construct Binary Tree from preorder and inorder traversal