112. 路径总和
题目链接
解题思路
递归处理
对每一条路径进行判断。
当遍历到叶子结点(root->left == nullptr && root->right == nullptr
)时,如果该条路径的和等于给定值,则返回 true
,否则返回 false
。
相似题目:257. 二叉树的所有路径
实现代码(C++)
class Solution {
public:
bool traversal(TreeNode *root, int sum, int targetSum) {
if (root != nullptr) {
if (root->left == nullptr && root->right == nullptr) { // 为叶子结点
if (sum + root->val == targetSum) {
return true;
}
return false;
}
// 否则,就对左子树和右子树递归查找
return traversal(root->left, sum + root->val, targetSum) || traversal(root->right, sum + root->val, targetSum);
}
return false; // root为空则返回false
}
bool hasPathSum(TreeNode* root, int targetSum) {
if (root == nullptr) {
return false;
}
return traversal(root, 0, targetSum);
}
};
257. 二叉树的所有路径
题目链接
解题思路
递归处理。
到达叶子结点时,将路径加入到 ans
中。
实现代码(C++)
class Solution {
public:
vector<string> ans;
void dfs(TreeNode *root, string tempPath) {
if (root == nullptr) {
return;
}
string path = tempPath + "->" + to_string(root->val);
if (root->left == nullptr && root->right == nullptr) {
ans.push_back(path.substr(2, path.length() - 2)); // 把开头的 "->" 去掉
} else {
dfs(root->left, path);
dfs(root->right, path);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
if (root == nullptr) {
return vector<string>();
}
dfs(root, "");
return ans;
}
};