[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 };
原文地址:https://www.cnblogs.com/jcliBlogger/p/4639502.html