add: 230316

This commit is contained in:
Eatswap 2023-03-16 22:27:25 +08:00
parent b9564c775d
commit 693d676aad
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 43 additions and 1 deletions

42
cpp/2303/230316.cpp Normal file
View File

@ -0,0 +1,42 @@
#include <vector>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
explicit TreeNode(int x, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(x), left(left), right(right) {}
};
/**
* 106. Construct Binary Tree from Inorder and Postorder Traversal
*
* Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
*/
using VCI = std::vector<int>::const_iterator;
class Solution {
private:
static TreeNode* bT(VCI is, VCI ie, VCI ps, VCI pe) {
if (is == ie || ps == pe)
return nullptr;
int r = *(pe - 1);
int pos = std::find(is, ie, r) - is;
return new TreeNode(
r,
bT(is, is + pos, ps, ps + pos),
bT(is + pos + 1, ie, ps + pos, pe - 1)
);
}
public:
static TreeNode* buildTree(const std::vector<int>& inorder, const std::vector<int>& postorder) {
return bT(inorder.begin(), inorder.end(), postorder.begin(), postorder.end());
}
};
int main() {
Solution::buildTree({-1}, {-1});
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2303)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2303 230316-CN.cpp) ADD_EXECUTABLE(2303 230316.cpp)