Path Sum II

Q:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

A:

额,好吧,借用一下path sum的代码,中间再小小的修改一下,搞定。

struct TreeNode {
  int val;
  TreeNode *left;
  TreeNode *right;
  TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
 public:
  vector<vector<int> > pathSum(TreeNode *root, int sum) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    vector<vector<int> > results; 
    if (!root) return results; 
    stack<TreeNode*> s;
    stack<bool> r;
    int cur_sum = 0;
    vector<int> cur_path;
    TreeNode* cur = root;
    while (cur || !s.empty()) {
      while (cur) {
        s.push(cur);
        r.push(false);
        cur_sum += cur->val;
        cur_path.push_back(cur->val);
        cur = cur->left;
      }   
      while (!r.empty() && r.top()) {
        TreeNode* tmp = s.top();
        if (!tmp->left && !tmp->right) {
          if (cur_sum == sum) {
            results.push_back(cur_path);
          }   
        }   
        cur_sum -= tmp->val;
        cur_path.pop_back();
        s.pop();
        r.pop();
      }   
          
      if (!s.empty()) {
        cur = s.top()->right;
        r.top() = true;
      }   
    }   
    return results;
  }
};

 

posted @ 2013-06-17 13:04  dmthinker  阅读(104)  评论(0)    收藏  举报