题解 | #二叉树中和为某一值的路径(二)#

二叉树中和为某一值的路径(二)

https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
#include <cmath>
#include <functional>
class Solution {
public:
    vector<vector<int>> FindPath(TreeNode* root,int expectNumber) {
		vector<int> path;
		vector<vector<int>> res;
		function<void(TreeNode *, int)> dfs = [&](TreeNode *root, int expectNumber) -> void {
			if (!root) {
				return;
			}
			path.push_back(root->val);
			expectNumber -= root->val;
			if (!root->left && !root->right && expectNumber == 0) {
				res.push_back(path);
			} else {
				dfs(root->left, expectNumber);
				dfs(root->right, expectNumber);
			}
			path.pop_back();
		};
		dfs(root, expectNumber);
		return res;
    }
};

思路:递归。

当且仅当到达叶子节点,且路径和为expectNumber时,才将当前路径path放入结果集合res中,否则继续递归。

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-04 18:25
点赞 评论 收藏
分享
流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
06-14 19:09
门头沟学院 Java
darius_:给制造业搞的,什么物料管理生产管理,设备管理点检,最最关键的就是一堆报表看板。个人觉得没啥技术含量都是些基本的crud,但是业务很繁琐那种
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务