zoukankan      html  css  js  c++  java
  • LeetCode 113. 路径总和 II

    题目链接:https://leetcode-cn.com/problems/path-sum-ii/

    给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

    说明: 叶子节点是指没有子节点的节点。

    示例:
    给定如下二叉树,以及目标和 sum = 22,

    5
    /
    4 8
    / /
    11 13 4
    / /
    7 2 5 1
    返回:

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

     1 /**
     2  * Definition for a binary tree node.
     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 deal(TreeNode* root,vector<vector<int>>& res,vector<int> cur,int sum){
    13         if(root==NULL) return;
    14         sum-=root->val;
    15         cur.push_back(root->val);
    16         if(root->left==NULL&&root->right==NULL){
    17             if(sum==0) res.push_back(cur);
    18         }
    19         deal(root->left,res,cur,sum);
    20         deal(root->right,res,cur,sum);
    21     }
    22     vector<vector<int>> pathSum(TreeNode* root, int sum) {
    23         vector<vector<int>> res;
    24         vector<int> cur;
    25         deal(root,res,cur,sum);
    26         return res;
    27     }
    28 };
  • 相关阅读:
    A
    博弈论
    K
    快速幂
    基数排序
    计数排序
    KMP求字符串最小循环节
    二分图多重匹配
    hdu2818行列匹配+排序
    二分图行列匹配与最大匹配必须边
  • 原文地址:https://www.cnblogs.com/wydxry/p/12681495.html
Copyright © 2011-2022 走看看