Skip to content

Commit ddb6f2c

Browse files
committed
feat:add Solution.cpp for 0106.Construct Binary Tree from Inorder and Postorder Traversal
1 parent 6169b5e commit ddb6f2c

File tree

1 file changed

+18
-0
lines changed
  • solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal

1 file changed

+18
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public:
3+
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
4+
return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
5+
}
6+
TreeNode *buildTree(vector<int> &inorder, int iLeft, int iRight, vector<int> &postorder, int pLeft, int pRight) {
7+
if (iLeft > iRight || pLeft > pRight) return NULL;
8+
TreeNode *cur = new TreeNode(postorder[pRight]);
9+
int i = 0;
10+
for (i = iLeft; i < inorder.size(); ++i) {
11+
if (inorder[i] == cur->val)
12+
break;
13+
}
14+
cur->left = buildTree(inorder, iLeft, i - 1, postorder, pLeft, pLeft + i - iLeft - 1);
15+
cur->right = buildTree(inorder, i + 1, iRight, postorder, pLeft + i - iLeft, pRight - 1);
16+
return cur;
17+
}
18+
};

0 commit comments

Comments
 (0)