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);
        }
    };
  • 相关阅读:
    SPOJ AMR12B 720
    OUC_TeamTraining_#1 720
    Mac下安装必须软件
    spawn命令和expect
    python基础
    AndroidManifest.xml详解
    Ubuntu系统连接Android真机调试
    Android Studio 快捷键
    linux 解压/压缩命令
    sadasd
  • 原文地址:https://www.cnblogs.com/vercont/p/10210263.html
Copyright © 2011-2022 走看看