【leetcode】113. Path Sum II

本文探讨了在给定的二叉树中寻找所有从根节点到叶子节点的路径,这些路径上的节点值之和等于指定的目标和。通过递归算法,我们详细介绍了如何遍历树结构并收集符合条件的路径,同时提供了清晰的代码实现。

题目:
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

Note: A leaf is a node with no children.


思路:
遍历所有叶子节点,判断路径之和是否为sum。用一维数组t存放临时答案,用二维数组ans存放最终答案。


代码实现:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void f(TreeNode* root, int sum, vector<int> &t, vector<vector<int>> &ans){
        
        if (root->left == nullptr && root->right == nullptr){
            if (root->val == sum){
                t.push_back(root->val);
                ans.push_back(t);
                t.pop_back();
            }
        }else if(root->left == nullptr){
            t.push_back(root->val);
            f(root->right, sum-root->val, t, ans);
            t.pop_back();
        }else if(root->right == nullptr){
            t.push_back(root->val);
            f(root->left, sum-root->val, t, ans);
            t.pop_back();
        }else{
            t.push_back(root->val);
            f(root->right, sum-root->val, t, ans);
            f(root->left, sum-root->val, t, ans);
            t.pop_back();
        }
        
    }
    
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        
        vector<vector<int>> ans;
        if (root == nullptr){
            return ans;
        }
        vector<int> t;
        f(root, sum, t, ans);
        return ans;
    }
};

discuss:

// 常规思路
class Solution {
public:
    
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> paths;
        vector<int> path;
        findPaths(root, sum, path, paths);
        return paths;
    }
    
    void findPaths(TreeNode *node, int sum, vector<int> &path, vector<vector<int>> &paths){
        if (!node) return ;
        path.push_back(node->val);
        if (!node->left && !node->right && sum == node->val) paths.push_back(path);
        findPaths(node->left, sum-node->val, path, paths);
        findPaths(node->right, sum-node->val, path, paths);
        path.pop_back();
    }
    
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值