Leetcode dfs Path SumII,leetcodesumii
Path Sum II Total Accepted: 18489 Total Submissions: 68323My Submissions
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]]
題意:給定一棵二叉樹和一個值,在二叉樹中找到從根到葉子的路徑使得路徑中的節點的總值
等於給定值
思路:dfs
複雜度:時間O(n) 空間O(log n)
/** * 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<int> cur; _pathSum(root, sum,cur); return res; } private: vector<vector<int> > res; void _pathSum(TreeNode *root, int sum, vector<int> &path){ if(!root) return ; path.push_back(root->val); if(!root->left && !root->right){ if(root->val == sum) { res.push_back(path); } } _pathSum(root->left, sum - root->val, path); _pathSum(root->right, sum - root->val, path); path.pop_back(); }};