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

    水。

     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     void getPath(TreeNode *root, int sum, vector<vector<int> > &res, vector<int> path) {
    13         if (root == NULL) {
    14             return;
    15         }
    16         path.push_back(root->val);
    17         if (root->left == NULL && root->right == NULL) {
    18             if (root->val == sum) {
    19                 res.push_back(path);
    20             }
    21             return;
    22         }
    23         getPath(root->left, sum - root->val, res, path);
    24         getPath(root->right, sum - root->val, res, path);
    25     }
    26     
    27     vector<vector<int> > pathSum(TreeNode *root, int sum) {
    28         vector<vector<int> > res;
    29         vector<int> path;
    30         getPath(root, sum, res, path);
    31         return res;
    32     }
    33 };
  • 相关阅读:
    runtime-给系统已有类添加属性
    解决自定义leftBarButtonItem返回手势失效的方法
    类和对象
    内存拷贝
    响应者链
    属性
    懒加载
    封装思想
    屏幕旋转
    block
  • 原文地址:https://www.cnblogs.com/easonliu/p/3634961.html
Copyright © 2011-2022 走看看