[leetcode]Path Sum II
来源:互联网 发布:怎么看10月经济数据 编辑:程序博客网 时间:2024/06/03 16:08
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
DFS,当搜索到叶子节点时把路径存储下来。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool ans = false; vector<int> st; vector<vector<int>> v; vector<vector<int> > pathSum(TreeNode *root, int sum) { if(root == NULL) return v; st.push_back(root->val); if(root->left == NULL && root->right == NULL){ int a = 0; for(int i=0;i<st.size();i++){ a += st[i]; } ans = (a==sum); if(ans){ vector<int> ve; for(int i=0;i<st.size();i++){ ve.push_back(st[i]); } v.push_back(ve); } return v; } pathSum(root->left,sum); if(root->left != NULL) st.erase(st.end()-1); pathSum(root->right,sum); if(root->right != NULL) st.erase(st.end()-1); return v; }};
0 0
- 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
- 【leetcode】Path Sum II
- [LeetCode] Path Sum II
- MFC工程,字符集使用多字节,界面就变成WIN95风格的解决办法
- Java自学总结之三变量的生存空间与范围
- java读写hdfs简单demo
- WEB常用测试用例-文本输入框
- UVA - 455 Periodic Strings
- [leetcode]Path Sum II
- 第四章 自动化测试用例初探
- 启动apache (OS 10022)提供了一个无效的参数。解决方案
- Java的Variable Types变量类型-笔记
- ThreadLocal-分析
- iOS代理传值(委托传值)
- 单键索引还是组合索引
- LeetCode Length of Last Word
- IOS平台的几个推送服务的对比