[LeetCode] Path Sum

This problem has a very easy recursive code as follows.

复制代码
 1 class Solution {
 2 public:
 3     bool hasPathSum(TreeNode* root, int sum) {
 4         if (!root) return false;
 5         if (!(root -> left) && !(root -> right))
 6             return sum == root -> val;
 7         return hasPathSum(root -> left, sum - root -> val) ||
 8                hasPathSum(root -> right, sum - root -> val);
 9     }
10 };
复制代码

If you insist on an iterative solution, this link has a clean iterative solution in Python. I rewrite the code in C++ as follows. In fact, it uses pair<TreeNode*, int> to recor the information, which greatly simplifies the code.

复制代码
 1 class Solution {
 2 public:
 3     bool hasPathSum(TreeNode* root, int sum) {
 4         if (!root) return false;
 5         stack<pair<TreeNode*, int> > pairs;
 6         pairs.push(make_pair(root, sum));
 7         while (!pairs.empty()) {
 8             pair<TreeNode*, int> pr = pairs.top();
 9             pairs.pop();
10             TreeNode* node = pr.first;
11             int remain = pr.second;
12             if (!(node -> left) && !(node -> right) && remain == node -> val)
13                 return true;
14             if (node -> left)
15                 pairs.push(make_pair(node -> left, remain - node -> val));
16             if (node -> right)
17                 pairs.push(make_pair(node -> right, remain - node -> val));
18         }
19         return false;
20     }
21 };
复制代码

This link gives a longer iterative solution using postorder traversal.

复制代码
 1 class Solution {
 2 public:
 3     bool hasPathSum(TreeNode* root, int sum) {
 4         TreeNode* pre = NULL;
 5         TreeNode* cur = root;
 6         stack<TreeNode*> nodes;
 7         int s = 0;
 8         while (cur || !nodes.empty()) {
 9             while (cur) {
10                 nodes.push(cur);
11                 s += cur -> val;
12                 cur = cur -> left;
13             }
14             cur = nodes.top();
15             if (!(cur -> left) && !(cur -> right) && s == sum)
16                 return true;
17             if (cur -> right && pre != cur -> right)
18                 cur = cur -> right;
19             else {
20                 pre = cur;
21                 nodes.pop();
22                 s -= cur -> val;
23                 cur = NULL;
24             }
25         }
26         return false;
27     }
28 };
复制代码

 

posted @   jianchao-li  阅读(216)  评论(0编辑  收藏  举报
编辑推荐:
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
阅读排行:
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 接口重试的7种常用方案!
点击右上角即可分享
微信分享提示