zoukankan      html  css  js  c++  java
  • 【leetcode】Path Sum II

    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 binary tree
     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<int> tmp;
    14         vector<vector<int> > result;
    15         if(root==NULL)
    16         {
    17             return result;
    18         }
    19         DFS(root,sum,tmp,result);
    20         return result;
    21        
    22     }
    23    
    24     void DFS(TreeNode *root,int &sum, vector<int> tmp,vector<vector<int> > &result,int cur=0)
    25     {
    26         if(root==NULL)
    27         {
    28             return;
    29         }
    30  
    31         int val=root->val;
    32         tmp.push_back(val);
    33        
    34         if(root->left==NULL&&root->right==NULL)
    35         {
    36             if(cur+val==sum) result.push_back(tmp);
    37             return;
    38         }
    39         DFS(root->left,sum,tmp,result,cur+val);
    40         DFS(root->right,sum,tmp,result,cur+val);
    41     }
    42 };
  • 相关阅读:
    hdu--4336--概率dp
    hdu--3905--dp
    codeforces--279--
    hdu--5023--线段树
    正则表达式
    vim编辑器使用
    圆头像控件,自动监听点击跳转到Activity
    ImageView切换两种状态下的模式
    string字符串截取
    Class对象获取方法
  • 原文地址:https://www.cnblogs.com/reachteam/p/4199319.html
Copyright © 2011-2022 走看看