标签:style blog http io ar color sp for strong
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; } };
标签:style blog http io ar color sp for strong
原文地址:http://www.cnblogs.com/ganganloveu/p/4131039.html