mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
@ -348,8 +348,32 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
```python
|
||||||
|
// 递归法
|
||||||
|
# Definition for a binary tree node.
|
||||||
|
# class TreeNode:
|
||||||
|
# def __init__(self, val=0, left=None, right=None):
|
||||||
|
# self.val = val
|
||||||
|
# self.left = left
|
||||||
|
# self.right = right
|
||||||
|
class Solution:
|
||||||
|
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
|
||||||
|
def isornot(root,targetSum)->bool:
|
||||||
|
if (not root.left) and (not root.right) and targetSum == 0:return True // 遇到叶子节点,并且计数为0
|
||||||
|
if (not root.left) and (not root.right):return False //遇到叶子节点,计数不为0
|
||||||
|
if root.left:
|
||||||
|
targetSum -= root.left.val //只有左节点
|
||||||
|
if isornot(root.left,targetSum):return True //递归,处理节点
|
||||||
|
targetSum += root.left.val //回溯
|
||||||
|
if root.right:
|
||||||
|
targetSum -= root.right.val //只有右节点
|
||||||
|
if isornot(root.right,targetSum):return True //递归,处理右节点
|
||||||
|
targetSum += root.right.val //回溯
|
||||||
|
return False
|
||||||
|
|
||||||
|
if root == None:return False //别忘记处理空TreeNode
|
||||||
|
else:return isornot(root,targetSum-root.val)
|
||||||
|
```
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
JavaScript:
|
JavaScript:
|
||||||
|
Reference in New Issue
Block a user