zoukankan      html  css  js  c++  java
  • [LeetCode] 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]
    ]
    
    /**
     * 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> > res;
        int sum;
        vector<vector<int> > pathSum(TreeNode *root, int sum) {
            this->sum = sum;
            if(root==NULL)
                return res;
            vector<int> v(1,root->val);
            rootToP(root,root->val,v);
            return res;
        }
    private:
        void rootToP(TreeNode *p,int sum,vector<int> &v){
            if(p->left==NULL && p->right==NULL && this->sum == sum)
                res.push_back(v);
    
            vector<int> v0 = v;
            
            if(p->left != NULL){
                v0.push_back(p->left->val);
                rootToP(p->left,sum+p->left->val,v0);
            }
            v0 = v;
            if(p->right != NULL){
                v0.push_back(p->right->val);
                rootToP(p->right,sum+p->right->val,v0);
            }
        
        }
    };
  • 相关阅读:
    事件溯源的使用实例
    CQRS With Axon
    maven打包带依赖
    MongoDB Query语法和工具
    docker 在外部指定参数变量 spring
    logger 过滤部分类的logger
    Nginx ServerName指令
    Nginx 处理Http请求简单流程
    Listen 指令
    Nginx 配置
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3890334.html
Copyright © 2011-2022 走看看