剑指offer-24:二叉树中和为某一值的路径
DFS深度搜索遍历整个二叉树,采用遍历一个点便把该节点的val从sum中减去,当遍历到叶子节点且包括叶子节点之前sum为0时,该遍历的路径即为二叉树所求路径(之一),由于只遍历一遍,因此时间复杂度为O(n)。
具体代码如下:
class Solution {
public:
vector<vector<int>> ans;
vector<int> path;
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
dfs(root, expectNumber);
return ans;
}
void dfs(TreeNode* root, int num){
if(!root) return; //opps
path.push_back(root->val);
num -= root->val;
if(!root->left && !root->right && !num) ans.push_back(path); //opps
dfs(root->left, num);
dfs(root->right, num);
path.pop_back();
}
};