LeetCode 105. 重建二叉树from VLR && LVR
1 | TreeNode* buildTree (vector<int>& preorder, vector<int>& inorder) { |
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.
LeetCode 106 重建二叉树from LVR && LRV
1 | TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { |