• [Leetcode 34] 113 Path Sum II


    Problem:

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

    Analysis:

    This is tree's DFS problem. Either can use a recursive function or a stack to finish the traversal.

    Time complexity is O(n), where n is the number of nodes in the tree;

    Code:

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<vector<int> > pathSum(TreeNode *root, int sum) {
    13         // Start typing your C/C++ solution below
    14         // DO NOT write int main() function
    15         vector<int> stack;
    16         vector<vector<int> > res;
    17          
    18         if (root == NULL) return res;
    19         
    20         helper(root, 0, sum, stack, res);
    21         return res;
    22     }
    23     
    24     void helper(TreeNode *node, int pathSum, int sum, vector<int> path, vector<vector<int> > &res) {
    25         if (node->left == NULL && node->right == NULL) {
    26             if (pathSum+node->val == sum) {
    27                 path.push_back(node->val);
    28                 res.push_back(path);
    29             }
    30         }
    31         
    32         path.push_back(node->val);
    33         
    34         if (node->left != NULL)
    35             helper(node->left, pathSum + node->val, sum, path, res);
    36         
    37         if (node->right != NULL)
    38             helper(node->right, pathSum + node->val, sum, path, res);
    39     }
    40 };
    View Code

    Attention:

  • 相关阅读:
    python 安装Crypto.Ciphe
    ProxyPool 爬虫代理IP池配置采坑
    2020渗透测试面试问题大全
    Windows Server 2016抓取明文密码
    应用安全 – 端口漏洞整理
    .net core docker+ gogs + jenkins 自动化部署
    .net HttpClient 回传实体帮助类
    .net list转树状结构
    ABP 临时禁用TenantId IsDelete过滤
    ABP 使用cache缓存
  • 原文地址:https://www.cnblogs.com/freeneng/p/3096137.html
Copyright © 2020-2023  润新知