Code & Func
2020-01-07

第58天。

今天的题目是Construct Binary Tree from Inorder and Postorder Traversal:

一道很久之前嫌麻烦没做的题目,因为之前做过从中序遍历和先序遍历中重构二叉树了,所以从中序遍历和后序遍历重构二叉树就之前换一下取值的位置而已:

1
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
2
return buildTree(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
3
}
4
int search(vector<int> &inorder, int beg, int end, int val) {
5
while(beg <= end && inorder[beg] != val) beg++;
6
return beg;
7
}
8
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder, int ibeg, int iend, int pbeg, int pend) {
9
if (ibeg > iend || pbeg > pend) return nullptr;
10
if (ibeg == iend || pbeg == pend) return new TreeNode(postorder[pend]);
11
int val = postorder[pend];
12
int mid = search(inorder, ibeg, iend, val);
13
TreeNode *node = new TreeNode(val);
14
int leftsize = mid - ibeg;
15
node->left = buildTree(inorder, postorder, ibeg, mid-1, pbeg, pbeg + leftsize-1);
3 collapsed lines
16
node->right = buildTree(inorder, postorder, mid + 1, iend, pbeg + leftsize, pend-1);
17
return node;
18
}
上一条动态