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;
    };
  • 相关阅读:
    curl 空格和转义符
    supervisor
    pandas 小笔记
    bert 进行文本相似度计算
    认股权证的会计处理
    企业所得税汇算清缴
    调整事项与非调整事项的区别
    centos 挂载windows 2003 smb
    如何获得带转义的json内容
    安装了vs2019 编译node-sass node-gyp 找不到编译器的解决方法
  • 原文地址:https://www.cnblogs.com/obama/p/3255965.html
Copyright © 2011-2022 走看看