【剑指offer】【树】34.二叉树中和为某一值的路径

题目链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/

递归

时间复杂度:O(n)
空间复杂度:O(n)

/**
 * 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>> ans;
    vector<int> path;
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        dfs(root, sum);
        return ans;
    }
    void dfs(TreeNode* root, int sum)
    {
        if(!root) return ;
        path.push_back(root->val);
        sum -= root -> val;
        //判断当前节点是不是叶子节点,并且是否满足sum=0
        if(!root -> left && !root -> right && !sum) ans.push_back(path);
        //递归处理左右子树
        dfs(root -> left, sum);
        dfs(root -> right, sum);
        //path还原
        path.pop_back();
    }

};
posted @ 2020-05-06 20:19  NaughtyCoder  阅读(94)  评论(0)    收藏  举报