TreeNode* traversal(vector<int>& preorder, int preBegin, int preEnd, vector<int>& inorder, int inBegin, int inEnd){ if (preBegin == preEnd) returnnullptr;
//找到当前根节点 int rootValue = preorder[preBegin]; TreeNode* node = newTreeNode(rootValue);
//判断是否为叶子节点 if (preEnd - preBegin == 1) return node;
//在中序遍历中找到对应节点 int divideNode; for (divideNode = 0; divideNode <= inEnd; ++divideNode) if (inorder[divideNode] == rootValue) break;
//左开右闭区间分割 [) //分割中序数组 int leftInorderBegin = inBegin; int leftInorderEnd = divideNode;
int rightInorderBegin = divideNode + 1; int rightInorderEnd = inEnd;
//分割前序数组 int leftPreorderBegin = preBegin + 1; int leftPreorderEnd = preBegin + (leftInorderEnd - leftInorderBegin) + 1;
int rightPreorderBegin = leftPreorderEnd; int rightPreorderEnd = preEnd;
TreeNode* traversal(vector<int>& postorder, int postorderBegin, int postorderEnd, vector<int>& inorder, int inBegin, int inEnd){ if (postorderBegin == postorderEnd) returnnullptr;