zoukankan      html  css  js  c++  java
  • 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.

    For 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]
    ]

    思路:DFS. 如果root为空,直接返回空数组,否则调用help函数。help函数将传入的root节点值压入cur数组,更新当前数组cur的和值now,如果root为叶子节点,且cur数组和为target,则将cur数组压入ret。如果左子结点不为空,递归调用 help(root->left,cur,now,target),右子结点不为空,递归调用 help(root->right,cur,now,target)。请注意,cur数组不能传入引用参数,应该传入形参。每个递归函数在运行过程中对cur数组的操作都是各自为政,互不干涉的。

     
    /**
     * 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>> ret;
        void help(TreeNode *root,vector<int> cur,int now,int target){
            now+=root->val;
            cur.push_back(root->val);
            if(!root->left&&!root->right){
                if(now==target)
                    ret.push_back(cur);
                return;
            }
            if(root->left)
                help(root->left,cur,now,target);
            if(root->right)
                help(root->right,cur,now,target);
        }
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            if(!root)
                return ret;
            vector<int> temp;
            help(root,temp,0,sum);
            return ret;
        }
    };

     



  • 相关阅读:
    Day18-lvs
    mysql日志
    【杂文】我们都有光明的前途(回忆录)
    【杂文】银色的 NOI2020(退役记)
    【杂文】SCOI2020 游记
    【学习笔记】字符串—广义后缀自动机
    【学习笔记】数论、数学—常见定理、结论、性质汇总
    【杂文】随心一记
    【杂文】CSP2019 蒟蒻AFO(假)记
    【模板整合计划】目录
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5043195.html
Copyright © 2011-2022 走看看