題目連結(https://leetcode.com/problems/path-sum/)
Given the root
of a binary tree and an integer targetSum
, return true
if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum
.
A leaf is a node with no children.
DFS + tree 時常使用遞迴法求解
root
,一個整數targetSum
true
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
5+4+11+2 = 22
Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.
true
。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 {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == nullptr)
return false;
return dfs(root, targetSum);
}
private:
bool dfs(TreeNode* node, int remainingsum){
if(node == nullptr)
return false;
remainingsum -= node->val; //減去正在經過的節點值
//左右子樹都是空指標,該點則為 leaf
if(node->left == nullptr && node->right == nullptr){
return remainingsum == 0; // 如果是葉子節點且剩餘和為 0,表示找到了目標路徑
}
// 遞迴檢查左子樹或右子樹
// 只要其中一條路徑滿足條件就返回 true
return dfs(node->left, remainingsum) || dfs(node->right, remainingsum);
}
};
#不使用輔助函數
class SolutionAlternative {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
// 空節點返回 false
if (root == nullptr) {
return false;
}
// 更新目標和(減去當前節點值)
targetSum -= root->val;
// 如果是葉子節點,檢查剩餘和是否為 0
if (root->left == nullptr && root->right == nullptr) {
return targetSum == 0;
}
// 遞迴檢查左右子樹
return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);
}
};
root | targetSum | hasPathSum? |
---|---|---|
[5,4,8,11,null,13,4,7,2,null,null,null,1] | 22 | true |
[] | 0 | false |
[1,2,3] | 3 | true |
[1,2,3] | 5 | false |
nullptr
判斷:
if(root == nullptr)
用來處理空樹的情況,當root 為空時直接返回 false
。dfs
遞迴函式/targetSum
更新:
0
。if(node->left == nullptr && node->right == nullptr)
,這一判斷用來檢查節點是否是葉子節點,葉子節點是沒有子節點的節點。ps. 部分內容經 AI 協助整理