zoukankan      html  css  js  c++  java
  • Leetcode 113. Path Sum II

    113. Path Sum II

    • Total Accepted: 88034
    • Total Submissions: 302190
    • Difficulty: Medium

    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]
    ]

    思路:和Leetcode 257. Binary Tree Paths类似。

    代码:

    不用回溯的形式:24 ms

     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 pathSum(vector<vector<int>>& res,TreeNode* root, vector<int> temp, int sum){
    13         temp.push_back(root->val);
    14         sum-=root->val;
    15         if(!root->left&&!root->right&&!sum){
    16             res.push_back(temp);
    17             return;
    18         }
    19         if(root->left) pathSum(res,root->left,temp,sum);
    20         if(root->right) pathSum(res,root->right,temp,sum);
    21     }
    22     vector<vector<int> > pathSum(TreeNode* root, int sum) {
    23         vector<vector<int> > res;
    24         vector<int> temp;
    25         if(root) pathSum(res,root,temp,sum);
    26         return res;
    27     }
    28 };

    用回溯的形式:16 ms

     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 pathSum(vector<vector<int>>& res,TreeNode* root, vector<int>& temp, int sum){
    13         temp.push_back(root->val);
    14         sum-=root->val;
    15         if(!root->left&&!root->right&&!sum){
    16             res.push_back(temp);
    17         }
    18         if(root->left) pathSum(res,root->left,temp,sum);
    19         if(root->right) pathSum(res,root->right,temp,sum);
    20         temp.pop_back();
    21     }
    22     vector<vector<int> > pathSum(TreeNode* root, int sum) {
    23         vector<vector<int> > res;
    24         vector<int> temp;
    25         if(root) pathSum(res,root,temp,sum);
    26         return res;
    27     }
    28 };
  • 相关阅读:
    转: sql语句获取本周、本月数据
    Java 程序中的静态代码块
    Java 控制台程序输出计时器代码
    网页出现“繁体字”?
    html5中video视频只有声音没有图像
    Clipboard 剪辑板
    区分window8中 ie10 window phone8
    void 0
    touch pointer
    全局作用域 eval
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5689419.html
Copyright © 2011-2022 走看看