LeetCode 113. 路径总和 II 二叉树搜索+记录路径

思路:

当搜索到叶子节点时,我们看当前的s是否为0即可。

代码:

/**
 * 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:
    void dfs(TreeNode* root,vector<vector<int>> &ans,vector<int>path,int sum)
    {
        if(!root)return ;
        path.push_back(root->val);
        int x=sum-root->val;//先减去这个节点的值,看是否符合条件
        if(!root->left&&!root->right&&!x)
        {
            ans.push_back(path);
        }
        dfs(root->left,ans,path,x);
        dfs(root->right,ans,path,x);
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> ans;
        vector<int>path;
        dfs(root,ans,path,sum);
        return ans;
    }
};
发布了1062 篇原创文章 · 获赞 72 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/105375108
今日推荐