題目難度: Medium
原題描述:
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]
]
題目大意:
給你一棵二叉樹,讓你返回所有從根結點到葉子結點的所有數的和等於sum的路徑。
解題思路:
直接dfs整棵樹,用一個vector存儲走過的結點的值,注意回退時要把上一次加入的數刪除,這樣當走到葉子結點時,判斷當前從根結點到葉子結點的和是否等於sum,如果相等,則將vector加入最終的結果中,這樣一直到dfs結束爲止。
時間複雜度分析:
dfs的時間複雜度爲O(n+E),這裏E = n-1,因此時間複雜度爲O(n),n爲樹的結點個數。
以下是代碼:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
vector< vector<int> > ans;
vector<int> v;
class Solution {
public:
void dfs(TreeNode* root , int sum, int addSum){
v.push_back(root->val);
addSum += root->val;
if(addSum==sum && v.size()>0 && (!(root->left)&&!(root->right)) ){
ans.push_back(v);
}
if(root->left){
dfs(root->left, sum, addSum);
v.pop_back();
}
if(root->right){
dfs(root->right, sum, addSum);
v.pop_back();
}
}
vector< vector<int> > pathSum(TreeNode* root, int sum) {
ans.clear();
v.clear();
if(root){
dfs(root, sum, 0);
}
return ans;
}
};