Path sum II |leetcode c++
来源:互联网 发布:老炮儿 网络剧 编辑:程序博客网 时间:2024/06/06 12:58
I use iterate method to solve this problem.
1.I use the hash table unordered_map to record whether the node is visited.
2.i made a mistake so that the program entered an endless loop, Please see the detail information in the comment of the code.
/** * 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>> ans; int sum_stack = 0; if(root == NULL) return ans; vector<int> cur(0); stack<TreeNode *> s; s.push(root); cur.push_back(root->val); sum_stack = root->val; unordered_map<TreeNode *,bool> visited; visited[root] = true; while(!s.empty()) { TreeNode * temp = s.top(); if(temp->left!=NULL && !visited[temp->left]) { s.push(temp->left); cur.push_back(temp->left->val); visited[temp->left] = true; sum_stack +=temp->left->val; continue; } if(temp->right != NULL && !visited[temp->right]) { s.push(temp->right); cur.push_back(temp->right->val); visited[temp->right] = true; sum_stack +=temp->right->val; continue; } if(sum_stack == sum && temp->left == NULL &&temp->right == NULL)//at first I write a else after this if sentence, then //it entered an endless loop. because it excurte ans.push_back(cur) over and over; ans.push_back(cur); sum_stack -= s.top()->val; s.pop(); cur.pop_back(); } return ans; }};
0 0
- [C++]LeetCode: 91 Path Sum II
- 【leetcode c++】113 Path Sum II
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [LeetCode]Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Leetcode: Path Sum II
- LeetCode-Path Sum II
- [leetcode] Path Sum II
- LeetCode - Path Sum II
- [LeetCode] Path Sum II
- Leetcode Path Sum II
- LeetCode | Path Sum II
- sublime 插件安装
- vijos p1116(codevs 1038 )一元三次方程求解 题解
- OpenCV使用detectMultiScale可能会报错_CrtIsValidHeapPointer的解决方法
- Linq使用Group By经验总结
- HTTP协议详解
- Path sum II |leetcode c++
- .net学习必备基础知识
- Java compiler level does not match the version of the installed Java project facet
- Android解析XML的方式 优缺点
- hadoop 调优
- Mac显示或隐藏文件终端指令
- JDK tomcat nginx配置
- 2014-7月~2014-10月总结
- java软件开发交流群 QQ群号 385115663 定期公布编程资料