LeetCode113 Path Sum II
Posted wangxiaobao的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode113 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.(Medium)
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] ]
分析:
回溯法处理即可,利用helper函数遍历所有路径,达到sum时添加到result里。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 vector<vector<int>> result; 12 void helper(TreeNode* root, int sum, vector<int>& vec) { 13 if (root == nullptr) { 14 return; 15 } 16 vec.push_back(root -> val); 17 sum -= root -> val; 18 if (root -> left == nullptr && root -> right == nullptr) { 19 if (sum == 0) { 20 result.push_back(vec); 21 } 22 else { 23 vec.pop_back(); 24 sum += root -> val; 25 return; 26 } 27 } 28 if (root -> left != nullptr) { 29 helper(root -> left, sum, vec); 30 } 31 if (root -> right != nullptr) { 32 helper(root -> right, sum, vec); 33 } 34 vec.pop_back(); 35 sum -= root -> val; 36 } 37 public: 38 vector<vector<int>> pathSum(TreeNode* root, int sum) { 39 vector<int> vec; 40 helper(root, sum, vec); 41 return result; 42 } 43 };
以上是关于LeetCode113 Path Sum II的主要内容,如果未能解决你的问题,请参考以下文章