112. 路径总和
难度:简单。
标签:深度优先搜索,二叉树。
先放一个错误的解法:
class Solution {
bool dfs(TreeNode* root, int k){
if(root == nullptr && k == 0){
return true;
}
if(root == nullptr)return false;
return dfs(root->left, k - root->val) || dfs(root->right, k - root->val);
}
public:
bool hasPathSum(TreeNode* root, int targetSum) {
return dfs(root, targetSum);
}
};
对于以下用例,结果返回的是true
[5,4,8,11,null,13,4,7,2,null,null,null,1]
9
true的路径是
因为上述代码只是判断了当前的节点为空且k为0,就返回true,而当前节点为空并不能证明其上一个点就是叶子结点。证明叶子结点还是需要判断节点的左右子树是否都为空。
正确解法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
bool dfs(TreeNode* root, int k){
if(root == nullptr)return false;
if(root->left == nullptr && root->right == nullptr && k == root->val){
return true;
}
return dfs(root->left, k - root->val) || dfs(root->right, k - root->val);
}
public:
bool hasPathSum(TreeNode* root, int targetSum) {
return dfs(root, targetSum);
}
};
结果:
113. 路径总和 II
难度:中等。
标签:二叉树,深度优先搜索,回溯。
正确解法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
vector<vector<int>> ans;
void dfs(TreeNode* node, vector<int>& path, int k){
if(node == nullptr)return;
path.emplace_back(node->val);
if(node->left == nullptr && node->right == nullptr && k == node->val){
ans.emplace_back(path);
}
dfs(node->left, path, k - node->val);
dfs(node->right, path, k - node->val);
path.pop_back();
}
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<int> path;
dfs(root, path, targetSum);
return ans;
}
};
结果: