【LeetCode】113. Path Sum II
2014-11-29 15:47
423 查看
Path Sum II
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
return
这题是在Path Sum的基础上稍作修改。
与上题增加的动作是保存当前stack中路径的加和curSum。
当curSum等于sum时,将cur加入ret。
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] ]
这题是在Path Sum的基础上稍作修改。
与上题增加的动作是保存当前stack中路径的加和curSum。
当curSum等于sum时,将cur加入ret。
/** * Definition for binary tree * 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) { vector<vector<int> > ret; if(!root) return ret; stack<TreeNode*> stk; vector<int> cur; cur.push_back(root->val); int curSum = root->val; unordered_map<TreeNode*, bool> visited; stk.push(root); visited[root] = true; while(!stk.empty()) { TreeNode* top = stk.top(); if(!top->left && !top->right) {//leaf if(curSum == sum) ret.push_back(cur); } if(top->left && visited[top->left] == false) { stk.push(top->left); visited[top->left] = true; cur.push_back(top->left->val); curSum += top->left->val; continue; } if(top->right && visited[top->right] == false) { stk.push(top->right); visited[top->right] = true; cur.push_back(top->right->val); curSum += top->right->val; continue; } stk.pop(); curSum -= top->val; cur.pop_back(); } return ret; } };
相关文章推荐
- [LeetCode] 113. Path Sum II 路径和 II
- leetcode_middle_88_113. Path Sum II
- leetcode113. Path Sum II
- [LeetCode]113.Path Sum II
- 【leetcode】113. Path Sum II【java】
- 【LeetCode】113. Path Sum II 基于Java和C++的解法及分析
- LeetCode 113. Path Sum II
- [Leetcode] 113. Path Sum II
- [LeetCode]112. Path Sum&113. Path Sum II
- Leetcode 113. Path Sum II
- leetcode 113. Path Sum II 二叉树求符合和值为sum的链
- LeetCode-113. Path Sum II
- LeetCode 113. Path Sum II
- 【LeetCode】113.Path Sum II(Medium)解题报告
- 【一天一道LeetCode】#113. Path Sum II
- [LeetCode]113. Path Sum II(列出二叉树根到叶路径和等于sum的所有路径)
- leetcode 113. Path Sum II
- leetcode-113. Path Sum II
- [leetcode] 113. Path Sum II
- leetcode 113. Path Sum II DFS深度优先遍历