LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
Solution1:我的答案
仿照105题写的答案
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return my_buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
}
TreeNode* my_buildTree(vector<int>& inorder, int iLeft, int iRight, vector<int>& postorder, int pLeft, int pRight) {
if (iLeft > iRight || pLeft > pRight) return NULL;
int i = 0;
for (i = iLeft; i <= iRight; i++) {//2B的我写着2B的代码
if (inorder[i] == postorder[pRight])
break;
}
TreeNode* cur = new TreeNode(postorder[pRight]);
cur->left = my_buildTree(inorder, iLeft, i - 1, postorder, pLeft, pLeft + i - iLeft - 1);
cur->right = my_buildTree(inorder, i + 1, iRight, postorder, pLeft + i - iLeft, pRight - 1);
return cur;
}
};