[LintCode 376] 二叉树的路径和(Python)

在给定的二叉树中寻找所有节点和等于目标值的路径。有效路径需从根节点到叶节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。
一个有效的路径,指的是从根节点到叶节点的路径。

样例
给定一个二叉树,和 目标值 = 5:

     1
    / \
   2   4
  / \
 2   3

返回:

[
  [1, 2, 2],
  [1, 4]
]

代码

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    # @param {TreeNode} root the root of binary tree
    # @param {int} target an integer
    # @return {int[][]} all valid paths
    def __init__(self):
        self.ans = []
        self.s = []

    # 递归解法
    def binaryTreePathSum(self, root, target):
        # Write your code here
        if root is None:
            return self.ans

        self.s.append(root.val)
        target -= root.val

        if target == 0 and root.left is None and root.right is None:
            self.ans.append(list(self.s)

        self.binaryTreePathSum(root.left, target)
        self.binaryTreePathSum(root.right, target)

        self.s.pop()
        return self.ans

    # 非递归解法
    def binaryTreePathSum1(self, root, target):
        # Write your code here
        s = []
        res = []
        top = -1
        sum = 0
        p = root
        while True:
            while p is not None:
                sum += p.val
                s.append(p)
                top += 1
                p = p.left
            f = True
            q = None
            while top != -1 and f :
                p = s[-1]
                if p.right == q:
                    if p.right is None and p.left is None and sum == target:
                        t = []
                        for i in s:
                            t.append(i.val)
                        res.append(t)
                    sum -= p.val
                    top -= 1
                    s.pop()
                    q = p
                else:
                    p = p.right
                    f = False
            if top == -1:
                break
        return res 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值