zoukankan      html  css  js  c++  java
  • leetcode_112. 路径总和

    给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
    
    说明: 叶子节点是指没有子节点的节点。
    
    示例: 
    给定如下二叉树,以及目标和 sum = 22,
    
                  5
                 / 
                4   8
               /   / 
              11  13  4
             /        
            7    2      1
    返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/path-sum
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    
    #递归
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def hasPathSum(self, root: TreeNode, sum: int) -> bool:
            if not root:
                return False
            if not root.left and not root.right:
                return sum==root.val
            return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)
    
    #广度优先搜索,双队列
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def hasPathSum(self, root: TreeNode, sum: int) -> bool:
            if not root:
                return False
            queue=[root]
            val_queue=[root.val]
            while queue:
                temp_queue=queue.pop(0)
                temp_val_queue=val_queue.pop(0)
                if temp_queue.left is None and temp_queue.right is None:
                    if temp_val_queue==sum:
                        return True
                    continue
                if temp_queue.left:
                    queue.append(temp_queue.left)
                    val_queue.append(temp_val_queue+temp_queue.left.val)
                if temp_queue.right:
                    queue.append(temp_queue.right)
                    val_queue.append(temp_val_queue+temp_queue.right.val)
            return False
    
  • 相关阅读:
    使用IDEA启动Tomcat时出现端口被占用的问题解决办法
    在Navicat中设置id主键为UUID自增
    关于IDEA构建的maven项目:WEB-INF下的jsp移动到webapp下出现404无法访问的问题
    Spring框架学习日志(2/4)
    Spring框架学习日志(1/4)
    jenkins+python+pytest+selenium 自动化执行脚本并发送报告
    Selenium 添加Cookie实现绕过登录流程
    CSS
    集合
    Javaweb初学
  • 原文地址:https://www.cnblogs.com/hqzxwm/p/14057199.html
Copyright © 2011-2022 走看看