剑指 Offer 34. 二叉树中和为某一值的路径

题目

在这里插入图片描述

我的方法

思路

用栈的方法遍历二叉树。

  • 每次遍历一个数,将它的值加在temp中,同时判断sum(temp)==target是否成立,再看该节点是否是叶子节点,如果二者都成立,则将temp加入到路径结果中
  • 每次遍历完一个节点的子树后,将该节点从栈中弹出的同时,也将节点的值从temp中弹出

  • 主要是在前序遍历的基础上改的。不能用简易版的前序遍历,根节点比右孩子提前弹出,导致路径不完整,结果不正确。
  • sum(temp)==target成立时,不能直接用result.append(temp),后面temp改动,result也会跟着改动。使用result.append(temp.copy())result.append(list(temp))
# 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 pathSum(self, root: TreeNode, target: int):

        if not root:return []
        stack = []
        result = []
        temp = []
        last_visit = root
        while stack or root:
            while root:
                stack.append(root)
                temp.append(root.val)
                if sum(temp)== target and ( not(root.left or root.right)):
                    # print(temp)
                    result.append(temp.copy())
                    # print(result)
                root = root.left
            root = stack[-1]
            
            if root.right != last_visit:
                root = root.right
                if not root:
                    last_visit = None
            else:
                temp_root = stack.pop()
                temp.pop()
                # print(temp_root.val)
                last_visit = temp_root
                root = None
        return result

参考解法

通过设置全局遍历,用递归的方法实现

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        res, path = [], []
        def recur(root, tar):
            if not root: return
            path.append(root.val)
            tar -= root.val
            if tar == 0 and not root.left and not root.right:
                res.append(list(path))
            recur(root.left, tar)
            recur(root.right, tar)
            path.pop()

        recur(root, sum)
        return res

作者:jyd
链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/solution/mian-shi-ti-34-er-cha-shu-zhong-he-wei-mou-yi-zh-5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值