Skip to content

Commit

Permalink
Added Path Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 20, 2023
1 parent 414e607 commit a501419
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -810,4 +810,15 @@ add_executable(ConstructBinaryTreeFromInorderAndPostorderTraversal
target_link_libraries(
ConstructBinaryTreeFromInorderAndPostorderTraversal
GTest::gtest_main
)

# Path Sum
add_executable(PathSum
Easy/PathSum/include/solution.hpp
Easy/PathSum/tests/test.cpp
)

target_link_libraries(
PathSum
GTest::gtest_main
)
50 changes: 50 additions & 0 deletions Easy/PathSum/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#pragma once

#include <stack>
#include <vector>
#include <iostream>
#include <algorithm>
#include <gtest/gtest.h>

struct TreeNode {
const int32_t value;
TreeNode *left;
TreeNode *right;
explicit TreeNode(int32_t value) :
value(value), left(nullptr), right(nullptr) { }
};

class Solution {
public:
static auto has_path_sum(TreeNode *root,
const int32_t target) -> bool {
if (root == nullptr) return false;

std::stack<TreeNode*> node_stack;
std::stack<int32_t> sum_stack;

node_stack.push(root);
sum_stack.push(target - root->value);

while (!node_stack.empty()) {
TreeNode *current_node = node_stack.top();
node_stack.pop();
int32_t current_sum = sum_stack.top();
sum_stack.pop();

if (!current_node->left && !current_node->right && current_sum == 0) {
return true;
} if (current_node->left) {
node_stack.push(current_node->left);
sum_stack.push(current_sum -
current_node->left->value);
} if (current_node->right) {
node_stack.push(current_node->right);
sum_stack.push(current_sum -
current_node->right->value);
}
}

return false;
}
};
17 changes: 17 additions & 0 deletions Easy/PathSum/tests/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#include "../include/solution.hpp"

auto main() -> int {
auto *root = new TreeNode(5);
root->left = new TreeNode(4);
root->left->left = new TreeNode(11);
root->left->left->left = new TreeNode(7);
root->left->left->right = new TreeNode(2);
root->right = new TreeNode(8);
root->right->left = new TreeNode(13);
root->right->right = new TreeNode(4);
root->right->right->right = new TreeNode(1);

std::cout << std::boolalpha << Solution::has_path_sum(root, 22);

return 0;
}

0 comments on commit a501419

Please sign in to comment.