輸入一棵二叉樹和一個整數,打印出二叉樹中節點值的和爲輸入整數的所有路徑。從樹的根節點開始往下一直到葉節點所經過的節點形成一條路徑。
示例:
給定如下二叉樹,以及目標和 sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
提示:
節點總數 <= 10000
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
分析:
深度遞歸,先序遍歷
解答:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void dfs(TreeNode* root, int sum){
if(root==NULL){
return;
}
path.push_back(root->val);
sum -= root->val;
if(!root->left && !root->right && !sum){
res.push_back(path);
}
dfs(root->left,sum);
dfs(root->right,sum);
path.pop_back();//回溯用
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(root==NULL) return {};
dfs(root, sum);
return res;
}
};