leedcode 路径的和

使用迭代:

class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        # 如果根节点为空,直接返回False
        if not root:
            return False

        # 使用栈来进行迭代,每个元素是一个元组(node, path)
        stack = [(root, [root.val])]

        while stack:
            node, path = stack.pop(0)

            # 如果当前节点是叶子节点
            if not node.left and not node.right:
                print("Path:", path, "Sum:", sum(path))
                # 如果路径和等于目标值,返回True
                if sum(path) == targetSum:
                    return True

            # 处理右子树
            if node.right:
                stack.append((node.right, path + [node.right.val]))

            # 处理左子树
            if node.left:
                stack.append((node.left, path + [node.left.val]))

        # 如果遍历完整个树都没有找到符合条件的路径,返回False
        return False

 

posted @ 2024-02-22 15:00  Junior_bond  阅读(8)  评论(0)    收藏  举报