九章算法 | 字节跳动面试题:路径总和 II

这道题目要求在给定的二叉树中找出所有从根节点到叶子节点且路径总和等于特定目标值的路径。解题策略包括递归地遍历左右子树,并在遇到叶子节点时更新结果列表。
摘要由CSDN通过智能技术生成

描述

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

叶子节点是指没有子节点的节点。

在线评测地址

样例1

输入: root = {5,4,8,11,#,13,4,7,2,#,#,5,1}, sum = 22
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
输出: [[5,4,11,2],[5,8,4,5]]
解释:
两条路径之和为 22:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22

样例2

输入: root = {10,6,7,5,2,1,8,#,9}, sum = 18
              10
             /  \
            6    7
          /  \   / \
          5  2   1  8
           \ 
            9 
输出: [[10,6,2],[10,7,1]]
解释:
两条路径之和为 18:
10 + 6 + 2 = 18
10 + 7 + 1 = 18

当访问的节点是叶子节点的时候,新建一个列表,插入到result中,然后返回result。 分别遍历左右子树的节点,然后将他们分别插入到叶子节点之前。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: a binary tree
     * @param sum: the sum
     * @return: the scheme
     */
    vector<vector<int>> pathSum(TreeNode * root, int sum) {
        // Write your code here.
        vector<int> path;
        vector<vector<int>> Spath;
        int weight = 0;
        findpath(Spath,root,sum,path,weight);
        return Spath;
    }
    void findpath(vector<vector<int>> &Spath,TreeNode* root,int sum,vector<int> &path,int weight)
    {

        if(root == NULL){
            return;
        }
        weight = weight + root->val;
        path.push_back(root->val);
        if(weight == sum && root->left == NULL && root->right == NULL)
        {
            Spath.push_back(path);
            weight = weight - root->val;
            path.pop_back();
            return;
        }
        findpath(Spath,root->left,sum,path,weight);
        findpath(Spath,root->right,sum,path,weight);
        path.pop_back(); 
    }
};

更多题解参考

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值