This problem is solved by recursive thinking, each time take the first element of the preface sequence as the root node of the current subtree, and then find the corresponding node in the sequence, in order to determine the root node corresponding to the Saozi right subtree of the sequence length, recursively constructs the root node Saozi right subtree.
TreeNode *execbuild (vector<int> &preorder, int prestart, int preend, vector<int> &inorder, int Instart, int inend) {TreeNode *result = new TreeNode (Preorder[prestart]); if (Prestart = = preend) {return result; } int i; for (i = instart; I <= inend; i++) {if (inorder[i] = = Preorder[prestart]) break; } if (i = = Instart) {result---left = nullptr; }else{Result--left = Execbuild (preorder, Prestart + 1, Prestart + I-instart, inorder, Instart, i-1); } if (i = = inend) {result, right = nullptr; }else{Result-right = Execbuild (preorder, Preend-(inend-i) + 1, preend, inorder, i + 1, inend); } return result; } TreeNode *buildtree (vector<int> &preorder, vector<int> &inorder) {//write your code here IntSize = Preorder.size (); if (Size < 1) return nullptr; Return Execbuild (preorder, 0, size-1, inorder, 0, size-1); }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Pre-sequence traversal and middle sequence traversal tree construction two-fork tree