TreeNode* (vector<int>& preorder, vector<int>& inorder){ return create (preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1); } TreeNode* create(vector<int>& preorder, vector<int>& inorder, int ps, int pe, int is, int ie){ if (ps > pe) { returnnullptr; } TreeNode* node = new TreeNode(preorder[ps]); int pos; for (int i = is; i <= ie; i++) { if (inorder[i] == node->val) { pos = i; break; } } node->left = create (preorder, inorder, ps + 1, ps + pos - is, is, pos - 1); node->right = create (preorder, inorder, pe - ie + pos + 1, pe, pos + 1, ie); return node; }
Let me explain the coordinates in the recursion. Very simply, we can see that the inorder traversal is divided into two parts, [is, pos-1] and [pos+1, ie] according to the root node pointed by pos.The first part contains pos - is elements, and the second part has ie- (pos +1)+1 = ie - pos elements. Correspondingly, in preorder traversal, the elements in the [ps+1, ps+pos - is] intervals belong to the left subtree, and the elements in the [pe - (ie - pos)+1, pe] interval belong to the right subtree.
近期评论