Leetcode 112. Path Sum
题目:解法:简单递归
题目:
解法:简单递归
class Solution:
def hasPathSum(self
, root
: TreeNode
, sum: int) -> bool:
def helper(node
,curr_sum
):
if not node
.left
and not node
.right
:
return curr_sum
+node
.val
== sum
flag
= False
if node
.left
:
flag
= flag
or helper
(node
.left
,curr_sum
+node
.val
)
if node
.right
:
flag
= flag
or helper
(node
.right
,curr_sum
+node
.val
)
return flag
if not root
:
return False
return helper
(root
,0)
C++版本:
class Solution {
public:
bool hasPathSum(TreeNode
* root
, int sum
) {
if (!root
) return false;
return helper(root
,0,sum
);
}
bool helper(TreeNode
* node
,int curr_sum
,int sum
){
if (!node
->left
&& !node
->right
) return curr_sum
+node
->val
==sum
;
bool flag
=false;
if (node
->left
){
flag
= flag
|| helper(node
->left
,curr_sum
+node
->val
,sum
);
}
if (node
->right
){
flag
= flag
|| helper(node
->right
,curr_sum
+node
->val
,sum
);
}
return flag
;
}
};
转载请注明原文地址:https://tech.qufami.com/read-4470.html