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

    1.题目描述

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

    2.解法分析

    深度搜索即可,用一个变量记录curVec当前路径,一旦获得满足条件的路径,记录到最终结果中。

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int> > pathSum(TreeNode *root, int sum) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            result.clear();
            if(!root)return result;   
            int curSum = sum;
            vector<int> curVec;
            myPathSum(root,curSum,curVec);    
            return result;   
        }
        
        void myPathSum(TreeNode *root,int &curSum,vector<int> & curVec)
        {
            curVec.push_back(root->val);
            curSum-=root->val;
            
            if(!root->left&&!root->right)
            {
                if(curSum==0)
                {
                    result.push_back(curVec);
                }
                return ;
            }
            
            if(root->left){
                myPathSum(root->left,curSum,curVec);
                curSum+=root->left->val;curVec.pop_back();
            }
            if(root->right){
                myPathSum(root->right,curSum,curVec);
                curSum+=root->right->val;curVec.pop_back();
            }  
        }
        
        private:
            vector<vector<int>> result;
    };
  • 相关阅读:
    ftp
    vmware虚拟机如何安装ubuntu14.10系统
    第1章 初识java----Java简介
    fiddler
    Program Files 与Program Files (x86)
    跟我一起认识axure(三)
    React-FlipOver-Counter(日历翻页)
    vue2-vux-fitness-project
    cloud-music
    跟我一起认识axure(二)
  • 原文地址:https://www.cnblogs.com/obama/p/3255965.html
Copyright © 2011-2022 走看看