首页 > 代码库 > 【LeetCode】Path Sum II
【LeetCode】Path Sum II
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 sum = 22
,
5 / 4 8 / / 11 13 4 / \ / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5]]
这题是在Path Sum的基础上稍作修改。
与上题增加的动作是保存当前stack中路径的加和cur。
当pathSum等于sum时,将cur加入result。
/** * 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> > result; vector<int> cur; if(root == NULL) return result; int pathSum = 0; stack<TreeNode*> s; unordered_set<TreeNode*> visited; //visit root s.push(root); pathSum += root->val; visited.insert(root); cur.push_back(root->val); //whenever add a node into pathSum, check it if(root->left == NULL && root->right == NULL) {//root itself is leaf if(pathSum == sum) { result.push_back(cur); } } while(!s.empty()) { TreeNode* top = s.top(); if(top->left) {//has left if(visited.find(top->left) == visited.end()) {//not visited //visit s.push(top->left); pathSum += top->left->val; visited.insert(top->left); cur.push_back(top->left->val); //judge leaf if(top->left->left == NULL && top->left->right == NULL) {//leaf if(pathSum == sum) result.push_back(cur); } continue; } } if(top->right) {//has right if(visited.find(top->right) == visited.end()) {//not visited //visit s.push(top->right); pathSum += top->right->val; visited.insert(top->right); cur.push_back(top->right->val); //judge leaf if(top->right->left == NULL && top->right->right == NULL) {//leaf if(pathSum == sum) result.push_back(cur); } continue; } } s.pop(); //no need to go down, pop pathSum -= top->val; cur.pop_back(); } return result; }};
【LeetCode】Path Sum II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。