1. 程式人生 > 其它 >LeetCode 112[Python]. 路徑總和 給定一個二叉樹和一個目標和,判斷該樹中是否存在根節點到葉子節點的路徑,這條路徑上所有節點值相加等於目標和。

LeetCode 112[Python]. 路徑總和 給定一個二叉樹和一個目標和,判斷該樹中是否存在根節點到葉子節點的路徑,這條路徑上所有節點值相加等於目標和。

技術標籤:演算法二叉樹演算法leetcode資料結構python

LeetCode 112. 路徑總和

給定一個二叉樹和一個目標和,判斷該樹中是否存在根節點到葉子節點的路徑,這條路徑上所有節點值相加等於目標和。

說明: 葉子節點是指沒有子節點的節點。

示例:
給定如下二叉樹,以及目標和 sum = 22,

          5
         / \
        4   8
       /   / \
      11  13  4
     /  \      \
    7    2      1

返回 true, 因為存在目標和為 22 的根節點到葉子節點的路徑 5->4->11->2。

Code

def hasPathSum(self, root: TreeNode, sum: int) -> bool:#DFS
    if root is None:
        return False
    if root.left is None and root.right is None:#迴圈條件
        return sum==root.val#終止條件
    return self.hasPathSum(root.left,sum-root.val) or  self.hasPathSum(root.right,sum-root.val)

Code2

def hasPathSum(self, root: TreeNode, sum: int) -> bool:#bfs
    if root is None:
        return False
    queue=[]
    queue.append(root)
    queue.append(root.val)
    while queue:
        node=queue.pop(0)
        res=queue.pop(0)
        if not node.left and not node.right and res==sum:#終止條件
            return True
        if node.left:
            queue.append(node.left)
            queue.append(node.left.val+res)                
        if node.right:
            queue.append(node.right)
            queue.append(node.right.val+res)   
    return False

想法

不管使用dfs or bfs 都是為了遍歷所有條件。