剑指OFFER----面试题34. 二叉树中和为某一值的路径
链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> res; vector<int> path; vector<vector<int>> pathSum(TreeNode* root, int sum) { dfs(root, sum); return res; } void dfs(TreeNode* root, int sum) { if (!root) return; path.push_back(root->val); sum -= root->val; if (!root->left && !root->right && !sum) res.push_back(path); dfs(root->left, sum); dfs(root->right, sum); path.pop_back(); } };