題幹
path-sum i
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
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.
For example:
Given the below binary tree andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
問題一:樹根結點到子結點的所有路徑中和是否等於已給的sum。
問題二:在問題一的基礎上,打印所有符合條件的路徑值。
數據結構
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
解題思路
問題一
深度遍歷dfs即可解決。
問題二
在深度遍歷dfs的基礎上,用verctor來存儲路徑,再用一個vector 存儲符合條件的路徑。
參考代碼
問題一:
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if(root==NULL)
return false;
if (root->left==NULL&&root->right==NULL&&sum-root->val==0)
return true;//符合條件
return (hasPathSum(root->left, sum-root->val)||hasPathSum(root->right, sum-root->val));//左右子樹遍歷
}
};
問題二:
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int>> vv;
vector<int>v;
dfs(root,sum,vv,v);
return vv;
}
void dfs(TreeNode *root,int sum,vector<vector<int>>& vv,vector<int>v)
{
if (root==NULL)
return;
v.push_back(root->val);//記錄路徑值
if (root->left==NULL&&root->right==NULL&&sum-root->val==0)
vv.push_back(v);//記錄符合條件的路徑
dfs(root->left, sum-root->val,vv,v);//左右子樹遍歷
dfs(root->right, sum-root->val,vv,v);
}
};
易錯點
對於vv的調用要用引用&,因爲v的路徑存儲是不同級的遞歸調用。但是vv存在同級調用,值會改變無法傳遞,所以要用原地址引用。