Construct Binary Tree from preorder and inorder traversalTotal accepted:32279 Total submissions:122094my submissions QuestionSolution
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 SearchHas you met this question in a real interview? Yes No
Discuss
This question gives you the result of the binary tree's pre-sequence traversal and the middle sequence traversal (given in the form of vectors, where there are no points that don't exist), so the first is definitely the root node in the pre-sequence traversal.
This problem is done in a recursive way, because the first point in the pre-order traversal, in the middle sequence traversal, its left is its left subtree, the right of its right subtree, so that in turn recursively can construct a two-fork tree.
Here is the solution to the AC
#include <iostream> #include <vector>using namespace std;struct TreeNode {int val; TreeNode *left; TreeNode *right; TreeNode (int x): Val (x), left (null), right (null) {}};/* find a position in the VEC */int laocation_vector (vector<int>& VEC, int A,int I,int j) {for (int k=i;k<=j;++k) if (vec[k]==a) return k;return-1;} /*i,j is the range, K is the beginning of the calculation of the first few */void pre_construct (vector<int>& preorder,vector<int>& inorder,TreeNode** Root,int I,int j,int& k) {if (K>=preorder.size ()) {*root=null;return;} int Loacte_in=laocation_vector (INORDER,PREORDER[K],I,J); if (loacte_in<i| | LOACTE_IN>J) {*root=null;return;} *root= (treenode*) malloc (sizeof (TreeNode));(*root)->val=preorder[k];k++;p re_construct (preorder,inorder,& (*root)->left,i,loacte_in-1,k);p re_construct (preorder,inorder,& (*root)->right,loacte_in+1,j,k); return;} /* This function primarily calls */treenode* Buildtree (vector<int>& preorder, vector<int>& inorder) {TreeNode* root= Null;if (Preorder.size () ==null)Return Root;int k=0;pre_construct (preorder,inorder,&root,0, (Preorder.size ()-1), k); return root;} int main () {vector<int> vec_pre;vector<int> vec_in;vec_pre.push_back (1), Vec_pre.push_back (2); vec_ In.push_back (2), Vec_in.push_back (1); treenode* Root;root=buildtree (vec_pre,vec_in);}
leetcode_105 problem--construct Binary tree from preorder and inorder traversal (tree, recursive)