Skip to content

Commit

Permalink
Added Construct Binary Tree from Preorder and Inorder Traversal
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 20, 2023
1 parent 7e6cacc commit 8b9548c
Showing 1 changed file with 4 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,16 @@ struct TreeNode {
class Solution {
public:
static auto build_tree(const std::vector<int32_t> &preorder,
const std::vector<int32_t> &inorder) -> TreeNode* {
const std::vector<int32_t> &inorder) -> TreeNode* {
auto pre = preorder.begin();
auto in = inorder.begin();

std::function<TreeNode*(int32_t)> construct = [&](int32_t stop) -> TreeNode* {
std::function<TreeNode*(const int32_t)> construct =
[&](const int32_t stop) -> TreeNode* {
if (pre == preorder.end() || *in == stop) return (TreeNode*)nullptr;
auto *node = new TreeNode{*(pre++)};
node->left = construct(node->value);
assert (*in == node->value);
assert(*in == node->value);
in++;
node->right = construct(stop);
return node;
Expand Down

0 comments on commit 8b9548c

Please sign in to comment.