先簡單回顧一下,今天預計分析的題目: 112. Path Sum
題目敘述:
測資的 Input/Output
DFS 遞迴 解法
if root is None: return False
newSum = prevSum + node.val
if node.left is None and node.right is None: return newSum == targetSum
True
回來,表示有找到符合加總的路徑,便無需往下做,跟著回傳 True
if node.left is not None and dfsFindPath(node.left, newSum): return True
True
回來,表示有找到符合加總的路徑,便無需往下做,跟著回傳 True
if node.right is not None and dfsFindPath(node.right, newSum): return True
False
return False
# 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: Optional[TreeNode], targetSum: int) -> bool:
if root is None: return False
def dfsFindPath(node, prevSum):
newSum = prevSum + node.val
if node.left is None and node.right is None: return newSum == targetSum
if node.left is not None and dfsFindPath(node.left, newSum): return True
if node.right is not None and dfsFindPath(node.right, newSum): return True
return False
return dfsFindPath(root, 0)
DFS 迭代解法
stack = [(root, 0)]
node, prevSum = stack.pop()
newSum = prevSum + node.val
True
if node.left is None and node.right is None and newSum == targetSum: return True
若當前節點不為葉子:
if node.left is not None: stack.append((node.left, newSum))
if node.right is not None: stack.append((node.right, newSum))
若完整迭代完畢,表示沒有找到相符的 path,回傳 False
return False
完整程式碼如下:
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None: return False
stack = [(root, 0), ]
while stack:
node, prevSum = stack.pop()
newSum = prevSum + node.val
if node.left is None and node.right is None and newSum == targetSum: return True
if node.left is not None: stack.append((node.left, newSum))
if node.right is not None: stack.append((node.right, newSum))
return False