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
    
  • 相关阅读:
    linux of函数实例
    Linux libenv 编译移植
    OpenTracing简单了解
    Byte Buddy简单学习
    JavaAgent简单学习
    TB2安装ubuntu16.04+kinetic的ROS包
    常用工具传送门
    ROS传送门
    结对第二次—文献摘要热词统计及进阶需求
    结对第一次—原型设计(文献摘要热词统计)
  • 原文地址:https://www.cnblogs.com/hqzxwm/p/14057199.html
Copyright © 2011-2022 走看看