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

    题目链接:

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

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

     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     vector<vector<int>> pathSum(TreeNode* root, int sum) {
    13         vector<vector<int> > result;
    14         vector<int> cur; // 中间结果
    15         pathSum(root, sum, cur, result);
    16         return result;
    17     }
    18 private:
    19     void pathSum(TreeNode *root, int gap, vector<int> &cur,
    20         vector<vector<int> > &result) {
    21         if (root == nullptr) return;
    22         cur.push_back(root->val);
    23         if (root->left == nullptr && root->right == nullptr) { // leaf
    24         if (gap == root->val)
    25             result.push_back(cur);
    26         }
    27         pathSum(root->left, gap - root->val, cur, result);
    28         pathSum(root->right, gap - root->val, cur, result);
    29         cur.pop_back();
    30     }
    31 };
  • 相关阅读:
    转贴:CSS伪类与CSS伪元素的区别及由来具体说明
    Docker + Consul 多数据中心模拟
    Spring之事件发布系统
    ExecutorService的submit方法的坑
    固定频率调用接口方案
    叠罗汉III之推箱子
    叠罗汉II
    叠罗汉I
    滑雪
    华为OJ:火车进站
  • 原文地址:https://www.cnblogs.com/wydxry/p/11841063.html
Copyright © 2011-2022 走看看