zoukankan      html  css  js  c++  java
  • LeetCode 113. Path Sum II路径总和 II (C++)

    题目:

    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.

    Example:

    Given the below binary tree and sum = 22,

          5
         / 
        4   8
       /   / 
      11  13  4
     /      / 
    7    2  5   1
    

    Return:

    [
       [5,4,11,2],
       [5,8,4,5]
    ]

    分析:

    和Path Sum的思路一样,链接在这里https://www.cnblogs.com/silentteller/p/10823183.html

    只不过这道题需要将满足目标和的路径打印出来,我们可以传入一个空数组,每执行一次函数,便将当前的元素,也就是root->val加入到数组,当满足条件时,将数组传入进我们定义好的结果数组当中,需要注意的是,空数组需要传参,而不是传引用。

    程序:

    /**
     * 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>> pathSum(TreeNode* root, int sum) {
            vector<vector<int>> res;
            vector<int> s;
            dfs(root, sum, s, res);
            return res;
        }
        void dfs(TreeNode* root, int sum, vector<int> s, vector<vector<int>> &res){
            if(root == nullptr) return;
            s.push_back(root->val);
            if(root->left == nullptr && root->right == nullptr){
                if(sum == root->val)
                    res.push_back(s);
            }
            else{
                 dfs(root->left, sum-root->val, s, res);
                 dfs(root->right, sum-root->val, s, res);
            }      
        }
    };
  • 相关阅读:
    python IDE安装-mac
    tokudb引擎安装-2
    MariaDB10.2.X-新特性2-支持check约束and with as
    MariaDB10.2.X-新特性1-支持分析函数
    MySQL5.7表空间加密
    MySQL 5.7 SYS scheme解析
    tcpdump抓SQL
    pt-online-schema-change
    查看锁信息
    onlineDDL测试
  • 原文地址:https://www.cnblogs.com/silentteller/p/10829084.html
Copyright © 2011-2022 走看看