2017.10.29 LeetCode

来源:互联网 发布:靠网络如何挣钱 编辑:程序博客网 时间:2024/06/03 21:44

附:由于昨天去外地参加比赛,耽误了,补上~

113. Path Sum II

Description

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,
这里写图片描述

题意: 在一棵二叉树上寻找是否存在从根节点到叶子节点的路径使得权值和为目标值,并存在二维数组里

分析: 引入一个path数组来记录下路径,如果找到头符合目标的话,记录下,这里运用到了vector中std::vector.pop_back的运用,删除最后一个元素,详细看代码

参考函数

class Solution {public:    void dfs(TreeNode* root,vector<vector<int> >& res,vector<int>& path,int sum) {        if(!root) return;        path.push_back(root->val);        if(!root->left && !root->right && sum == root->val) {            res.push_back(path);            path.pop_back();//注意            return;        }        dfs(root->left,res,path,sum-root->val);        dfs(root->right,res,path,sum-root->val);        path.pop_back();    }    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<vector<int> > res;        vector<int> path;        dfs(root,res,path,sum);        return res;    }};