剑指 Offer -- 二叉树中和为某一值的路径(二十四)

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

题目描述

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

代码(已在牛客上 AC)

DFS. 主要注意, 当递归到底的时候, 某节点的左右子树同时为空, 并且希望 root->val 刚好等于 expectNumber.

class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if (!root) return {};
        vector<vector<int>> res;
        vector<int> cur;
        dfs(root, cur, res, expectNumber);
        return res;
    }
private:
    void dfs(TreeNode *root, vector<int> &cur, vector<vector<int>> &res, int target) {
        if (!root) return;
        cur.push_back(root->val);
        // res.push_back(cur); 后面不能定式的写个 return, 而是应该继续执行下去
        // 利用 root->left 与 root->right 同时为空, 两个 dfs 可以直接 return,
        // 接着执行 cur.pop_back(), 需要的就是执行这个方法.
        if (!root->right && !root->left && root->val == target)
            res.push_back(cur); 

        dfs(root->left, cur, res, target - root->val);
        dfs(root->right, cur, res, target - root->val);
        cur.pop_back();
    }
};

你可能感兴趣的:(剑指,Offer,系列)