判斷一棵二叉樹是否有一條從根節點到某一葉子節點的路徑,該路徑上所有節點的和為一個特定值。
注意點:
無例子:
輸入: sum = 12
3
/ \
9 20
/ \
15 7
/
14
輸出: True (3->9)
直接通過遞歸來解決,判斷一個節點時,先把要求的值先減去該節點的值,如果剩下要求的值為0且當前的節點就是一個葉子節點,那麼從根節點到當前節點的路徑就符合題目的要求。否則就要繼續遞歸當前節點的左右節點。
<code class="language-python hljs "># Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
sum -= root.val
if sum == 0 and root.left is None and root.right is None:
return True
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
if __name__ == "__main__":
None</code>