112. Path Sum [easy] (Python)

该博客探讨了如何解决LeetCode中的'Path Sum'问题,即判断二叉树是否存在一条从根到叶节点的路径,使得路径上的节点值之和等于给定的目标值。文章提供了四种解法,包括深度优先搜索(DFS)的递归和非递归实现,广度优先搜索(BFS)以及后序遍历的方法,并附有相应的Python代码示例。

题目链接

https://leetcode.com/problems/path-sum/

题目原文

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,

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

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

题目翻译

给定一个二叉树及一个和数sum,判断这个树是否有一条从根到叶的路径,这条路径上所有数之和为sum。比如,给定sum=22,二叉树为:

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

那么应该返回true,因为存在路径 5->4->11->2 ,其和为22。

思路方法

思路一

用深度优先搜索(DFS)遍历所有可能的从根到叶的路径,要注意每深一层要从和中减去相应节点的数值。下面是递归实现的代码。

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if not root:
            return False
        if not root.left and not root.right:
            return True if sum == root.val else False
        else:
            return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)

思路二

DFS的非递归实现,用栈实现。

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        stack = [(root, sum)]
        while len(stack) > 0:
            node, tmp_sum = stack.pop()
            if node:
                if not node.left and not node.right and node.val == tmp_sum:
                    return True
                stack.append((node.right, tmp_sum-node.val))
                stack.append((node.left, tmp_sum-node.val))
        return False

思路三

BFS方法,用队列实现。

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        queue = [(root, sum)]
        while len(queue) > 0:
            node, tmp_sum = queue.pop()
            if node:
                if not node.left and not node.right and node.val == tmp_sum:
                    return True
                queue.insert(0, (node.right, tmp_sum-node.val))
                queue.insert(0, (node.left, tmp_sum-node.val))
        return False

思路四

如果说上面都是比较常规的方法,那么后序遍历算是比较新奇的解法了。虽然也用的栈,但后序遍历的一大好处是它直接将路径保存在栈中,每次进入不同的层不需要记录当前的和。算是与DFS各有所长吧。

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        pre, cur = None, root
        tmp_sum = 0
        stack = []
        while cur or len(stack) > 0:
            while cur:
                stack.append(cur)
                tmp_sum += cur.val
                cur = cur.left
            cur = stack[-1]
            if not cur.left and not cur.right and tmp_sum == sum:
                return True
            if cur.right and pre != cur.right:
                cur = cur.right
            else:
                pre = cur
                stack.pop()
                tmp_sum -= cur.val
                cur = None
        return False

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51595815

import os import cv2 import tqdm from retinaface import Retinaface from utils.utils_map import evaluation #-------------------------------------------# # 进行retinaface的map计算 # 需要现在retinaface.py里面修改model_path #-------------------------------------------# if __name__ == '__main__': mAP_retinaface = Retinaface(confidence = 0.01, nms_iou = 0.45) save_folder = './widerface_evaluate/widerface_txt/' gt_dir = "./widerface_evaluate/ground_truth/" imgs_folder = './data/widerface/val/images/' sub_folders = os.listdir(imgs_folder) test_dataset = [] for sub_folder in sub_folders: image_names = os.listdir(os.path.join(imgs_folder, sub_folder)) for image_name in image_names: test_dataset.append(os.path.join(sub_folder, image_name)) num_images = len(test_dataset) for img_name in tqdm.tqdm(test_dataset): image = cv2.imread(os.path.join(imgs_folder, img_name)) image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) results = mAP_retinaface.get_map_txt(image) save_name = save_folder + img_name[:-4] + ".txt" dirname = os.path.dirname(save_name) if not os.path.isdir(dirname): os.makedirs(dirname) with open(save_name, "w") as fd: file_name = os.path.basename(save_name)[:-4] + "\n" bboxs_num = str(len(results)) + "\n" fd.write(file_name) fd.write(bboxs_num) for box in results: x = int(box[0]) y = int(box[1]) w = int(box[2]) - int(box[0]) h = int(box[3]) - int(box[1]) confidence = str(box[4]) line = str(x) + " " + str(y) + " " + str(w) + " " + str(h) + " " + confidence + " \n" fd.write(line) evaluation(save_folder, gt_dir) 在这段代码的基础上获得easy、medium、hard的pr曲线,给出完整python代码·
最新发布
03-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值