題目:

python3 代碼:
# 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, sum: int) -> bool:
if not root:
return False
if not root.left and not root.right and sum == root.val:
return True
lefttree = self.hasPathSum(root.left, sum-root.val)
righttree = self.hasPathSum(root.right, sum-root.val)
if lefttree or righttree:
return True
else:
return False
思路:
使用遞回想法,由于函式是回傳bool型別的,所以只要將sum的值不斷往下減,這樣如果值減到0,這樣就回傳True, 就代表有Path 在BST里,否則,BST里是沒有Path的,
如果覺得不錯,就點贊或者關注或者留言~
謝謝~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/249910.html
標籤:python
上一篇:Python入門基礎篇 No.82 —— 特殊方法和運算子多載_特殊屬性
下一篇:使用邊緣計算網關分析CAN報文
