LeetCode 113 Path Sum II DFS
2022/5/6 6:12:57
本文主要是介绍LeetCode 113 Path Sum II DFS,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Given the root
of a binary tree and an integer targetSum
, return all root-to-leaf paths where the sum of the node values in the path equals targetSum
. Each path should be returned as a list of the node values, not node references.
A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
Explanation: There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
Solution
给定一个二叉树,以及一个定值 targetSum
,现要求出所有从root
到leaf
的路径,其总和为targetSum
.
非常熟悉的\(DFS\)问题,定义 \(DFS(node,sum,paths,path)\). 其中\(node\)为当前的节点,\(sum\)表示剩余的总和,如果此时\(sum==node.val\),并且为叶子节点,那么将路径\(path\)加入\(paths\). 还需注意的一点是path.pop_back()
进行回溯
点击查看代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int targetSum) { vector<vector<int>> paths; vector<int> path; dfs(root, targetSum, paths, path); return paths; } void dfs(TreeNode* root, int sum, vector<vector<int>> &paths, vector<int> &path){ if(! root) return; path.push_back(root->val); if(!(root->left)&&!(root->right)&&(sum==root->val)){ paths.push_back(path); } dfs(root->left, sum-(root->val), paths, path); dfs(root->right,sum-(root->val), paths, path); path.pop_back(); } };
这篇关于LeetCode 113 Path Sum II DFS的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23增量更新怎么做?-icode9专业技术文章分享
- 2024-11-23压缩包加密方案有哪些?-icode9专业技术文章分享
- 2024-11-23用shell怎么写一个开机时自动同步远程仓库的代码?-icode9专业技术文章分享
- 2024-11-23webman可以同步自己的仓库吗?-icode9专业技术文章分享
- 2024-11-23在 Webman 中怎么判断是否有某命令进程正在运行?-icode9专业技术文章分享
- 2024-11-23如何重置new Swiper?-icode9专业技术文章分享
- 2024-11-23oss直传有什么好处?-icode9专业技术文章分享
- 2024-11-23如何将oss直传封装成一个组件在其他页面调用时都可以使用?-icode9专业技术文章分享
- 2024-11-23怎么使用laravel 11在代码里获取路由列表?-icode9专业技术文章分享
- 2024-11-22怎么实现ansible playbook 备份代码中命名包含时间戳功能?-icode9专业技术文章分享