zoukankan      html  css  js  c++  java
  • path-sum-ii leetcode C++

    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 andsum = 22, 5 / 
    4 8 / / 
    11 13 4 / / 
    7 2 5 1 return

    [ [5,4,11,2], [5,8,4,5] ]

    C++

    /**
     * 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) {
            vector<vector<int>> dp;
            vector<int> path;
            getPath(root,sum,dp,path);
            return dp;
        }
        void getPath(TreeNode *root, int sum,vector<vector<int>>& dp,vector<int> path){
            if(NULL == root) return;
            path.push_back(root->val);
            if(NULL == root->left && NULL == root->right && root->val == sum )
                dp.push_back(path);
            getPath(root->left,sum - root->val,dp,path);
            getPath(root->right,sum - root->val,dp,path);
        }
    };
  • 相关阅读:
    CSS介绍
    docker入门
    nginx+uWSGI+django+virtualenv+supervisor发布web服务器
    niginx入门
    常用服务安装部署
    VIM
    linux基本命令
    linux目录分级
    OpenStack共享组件
    kvm认识和安装
  • 原文地址:https://www.cnblogs.com/vercont/p/10210263.html
Copyright © 2011-2022 走看看