• leetcode-113. 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]
    ]

    题意:找出所有和为指定sum的路径链。(112升级版)

    思路:君可曾记得引用传参result?(这不就搞定了吗!哈哈哈)

    Accepted Code:
     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> tempResult;
    15         pathSum(root,sum,result,tempResult);
    16         return result;
    17     }
    18     
    19     void pathSum(TreeNode* root,int sum,vector<vector<int>>& result,vector<int>& tempResult)
    20     {
    21         if(root==nullptr)
    22         return;
    23         tempResult.push_back(root->val);
    24         if(root->left==nullptr&&root->right==nullptr&&sum==root->val){
    25             result.push_back(vector<int>(tempResult));
    26             tempResult.erase(tempResult.end()-1);
    27             return;
    28         }else
    29         {
    30             pathSum(root->left,sum-root->val,result,tempResult);
    31             pathSum(root->right,sum-root->val,result,tempResult);
    32         }
    33         tempResult.erase(tempResult.end()-1);
    34     }
    35 };
  • 相关阅读:
    TPLINK TLWR710N设置详解
    hehe.....
    AS3写FTP登录过程
    QQ
    网页设计标准尺寸:
    女孩,你愿意做他的第几个女朋友
    監聽一個變量的值變化
    dispatchEvent
    10
    C#常用代码
  • 原文地址:https://www.cnblogs.com/hongyang/p/6421576.html
Copyright © 2020-2023  润新知