[Leetcode 112] Path Sum

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
//code section
}
 int restSum;
if(root == nullptr)
return false;
else
restSum = targetSum — root->val;
if(root->left == nullptr && root->right == nullptr)
{
if(restSum == 0)
return true;
else
return false;
}
else
return hasPathSum(root->left, restSum) || hasPathSum(root->right, restSum);
// preorder
if(root == nullptr)
return false;
std::vector<TreeNode*> stack;
std::map<TreeNode*, int> done;
stack.push_back(root);
while(!stack.empty())
{
TreeNode* node = stack.back();
if(done.count(node) != 0)
{
targetSum += node->val;
stack.pop_back();
}
else
{
targetSum -= node->val;
}

if(node->left == nullptr && node->right == nullptr)
{
if(targetSum == 0)
return true;
targetSum += node->val;
stack.pop_back();
}
//traverse
if(done.count(node) == 0)
{
if(node->right != nullptr)
{
stack.push_back(node->right);
done[node]++;
}
if(node->left != nullptr)
{
stack.push_back(node->left);
done[node]++;
}
}
}
return false;

--

--

--

Hi I am Samuel

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Changes to our Account- & Payment-Models

Git LFS — A Solution That Won’t Work To A Problem That Doesn’t Exist

Managing Multiple Environment in Snowpack

Adding an Octopus to the Zsh Prompt

Creator of the Week: 100+ Habits on a journey to improve your life

Getting started with Velociraptor

The First Signs of Alcoholic Liver Damage Are Not in the Liver

Homelab: Intel NUC with the ESXi hypervisor.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Samuel Liu

Samuel Liu

Hi I am Samuel

More from Medium

Remove a node in Linked List without traversing it

5/4 Binary Search Tree

Find Median Of Two Sorted Arrays — LeetCode Solutions

Leetcode — 3. Longest Substring Without Repeating Characters(Medium)