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 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> one_result;// 中间结果
    15         pathSum(root, result, sum, one_result);
    16         return result;
    17     }
    18 private:
    19     void pathSum(TreeNode *root, vector<vector<int>> &result, int sum, vector<int> &one_result) {
    20         if (root == nullptr) return;
    21         
    22         one_result.push_back(root->val);
    23         if (root->left == nullptr && root->right == nullptr && sum == root->val) {//叶节点
    24             result.push_back(one_result);
    25         }
    26         pathSum(root->left, result, sum - root->val, one_result);
    27         pathSum(root->right, result, sum - root->val, one_result);
    28         
    29         one_result.pop_back();
    30     }
    31 };
  • 相关阅读:
    redis
    JSP
    Cookie&Session
    Servlet
    HTTP
    TomCat
    CSS
    XML
    JDBC
    Mysql(对表的操作)
  • 原文地址:https://www.cnblogs.com/skycore/p/5059124.html
Copyright © 2011-2022 走看看