Skip to content

Commit

Permalink
Create make_tree for the fixed binary tree of the example.
Browse files Browse the repository at this point in the history
  • Loading branch information
iglesias committed Apr 24, 2024
1 parent f2f6232 commit db689a8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 16 deletions.
22 changes: 6 additions & 16 deletions leetcode/404.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#include <memory>
#include <vector>
#include <stdexcept>

#include <gtest/gtest.h>

Expand All @@ -19,23 +18,14 @@ int sumOfLeftLeaves(TreeNode *root) {
}

TEST(sumOfLeftLeaves, SampleInput) {
auto root{std::make_unique<TreeNode>(3)};

// FIXME const construction.
std::vector<std::unique_ptr<TreeNode>> otherNodes;
otherNodes.push_back(std::make_unique<TreeNode>(9));
otherNodes.push_back(std::make_unique<TreeNode>(20));
otherNodes.push_back(std::make_unique<TreeNode>(15));
otherNodes.push_back(std::make_unique<TreeNode>(7));

root->left = otherNodes[0].get();
root->right = otherNodes[1].get();
root->right->left = otherNodes[2].get();
root->right->right = otherNodes[3].get();

const auto& [root, _] = make_tree({3, 9, 20, 15, 7});
EXPECT_EQ(sumOfLeftLeaves(root.get()), 24);
}

TEST(make_tree, EmptyVector) {
EXPECT_THROW(static_cast<void>(make_tree({})), std::out_of_range);
}

int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
Expand Down
28 changes: 28 additions & 0 deletions leetcode/tree.h
Original file line number Diff line number Diff line change
@@ -1,9 +1,37 @@
#pragma once

#include <memory>
#include <utility>
#include <vector>

using std::pair;
using std::make_unique;
using std::unique_ptr;
using std::vector;

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

pair<unique_ptr<TreeNode>, vector<unique_ptr<TreeNode>>>
make_tree(const vector<int>& v) {
auto root{std::make_unique<TreeNode>(v.at(0))};

// FIXME const construction.
vector<unique_ptr<TreeNode>> otherNodes;
//TODO use actual data in v to construct the tree.
otherNodes.push_back(make_unique<TreeNode>(9));
otherNodes.push_back(make_unique<TreeNode>(20));
otherNodes.push_back(make_unique<TreeNode>(15));
otherNodes.push_back(make_unique<TreeNode>(7));

root->left = otherNodes[0].get();
root->right = otherNodes[1].get();
root->right->left = otherNodes[2].get();
root->right->right = otherNodes[3].get();

return std::make_pair(std::move(root), std::move(otherNodes));
}

0 comments on commit db689a8

Please sign in to comment.