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

  • 相关阅读:
    Linux基础-yum软件包管理
    Linux基础-rpm软件包管理
    Linux基础-简单的进程操作
    Linux基础-free窥内存-dd探硬盘
    Linux基础-swap交换分区
    Linux基础-软硬连接Block概念
    Linux基础操作-分区概念
    Linux基础-vim编辑器
    Linux基础操作命令-打包压缩
    RandomAccessFile 文件读写中文乱码解决方案!
  • 原文地址:https://www.cnblogs.com/freeneng/p/3096137.html
Copyright © 2011-2022 走看看