1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| TreeNode* subTree2(int& index, int left, int right, vector<int>& inorder, vector<int>& postorder) { if (left == right)return NULL; if (right - left == 1) { index--; return new TreeNode(inorder[left]); } TreeNode* root = new TreeNode(postorder[index]); int i = left; for (; i < right; i++) { if (inorder[i] == postorder[index]) break; } index--; root->right = subTree(index, i + 1, right, inorder, postorder); root->left = subTree(index, left, i, inorder, postorder); return root; } TreeNode * buildTree(vector<int>& inorder, vector<int>& postorder) { int vsize = inorder.size(); if (vsize == 0)return NULL; else if (vsize == 1) return new TreeNode(inorder[0]); int i = vsize - 1; return subTree2(i, 0, vsize, inorder, postorder); }
|