zoukankan      html  css  js  c++  java
  • 【leetcode❤python】 112. Path Sum

    #-*- coding: UTF-8 -*-
    # 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):
        sumList=[]
        def dfs(self,root):
            curSum=self.sumList[-1]
            
            if root.left!=None or root.right!=None:self.sumList.pop()
            else:return
            
            if root.left!=None:
                valsum=curSum+root.left.val
                self.sumList.append(valsum)
                self.dfs(root.left)
            if root.right!=None:
                valsum=curSum+root.right.val
                self.sumList.append(valsum)
                self.dfs(root.right)
       
        def hasPathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: bool
            """
            self.sumList=[]
            if root==None:return False
            else:
                self.sumList.append(root.val)
                self.dfs(root)
                if self.sumList.__contains__(sum):
                    return True
            return False

  • 相关阅读:
    Socket 的网络编程
    《Python 3.5从零开始学》笔记-第8章 面向对象编程
    Python 的8个关键要素
    分布式发布订阅模型网络的实现有哪些
    MongoDB知识整理
    C++模板类与Qt信号槽混用
    C++中 =default,=delete用法
    QT知识整理
    Python题整理
    STL库的应用
  • 原文地址:https://www.cnblogs.com/kwangeline/p/5993147.html
Copyright © 2011-2022 走看看