[LeetCode] Path Sum

本文提供了路径总和问题的三种不同解决方案:递归解法、使用pair记录信息的迭代解法以及利用后序遍历的迭代解法。每种方法都详细介绍了其实现思路,并附上了C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4639502.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值