zoukankan      html  css  js  c++  java
  • 二叉树到某一节点经过的路径

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    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
            
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
    
        def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
            if root == None:
                return []
            res,stack = [],[]
            def getPath(root,currentSum):
                stack.append(root.val)
                currentSum += root.val
                if (currentSum == sum) and not root.left and not root.right:
                    res.append(list(stack))
                
                if root.left:
                    getPath(root.left,currentSum)
                if root.right:
                    getPath(root.right,currentSum)
                stack.pop(-1)
            getPath(root,0)
            return res

    非递归的方式

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
    
        def pathSum(self, root: TreeNode, sum1: int) -> List[List[int]]:
            result,temp = [],[]
            def dfs(root, sum1):
                if root:
                    if not root.right and not root.left: #判断是否为叶节点
                        temp.append(root.val)
                        b=sum(temp)
                        if b == sum1:
                            result.append(temp[0:]) 
                        temp.pop()
                        return 
                    temp.append(root.val)# 进栈
                    dfs(root.left, sum1)
                    dfs(root.right, sum1)
                    temp.pop()# 出栈
            dfs(root, sum1)
            return result
            
  • 相关阅读:
    redis的常用命令及php-redis的使用
    mysql数据库基本操作
    php接口数据安全解决方案
    如何防止api接口被恶意调用或攻击
    virtualBox安装及调试
    PHP常用扩展
    memcached安装与应用
    Jmeter的基础使用(4)——添加服务器的监控
    Jmeter的基础使用(3)——使用实操
    Jmeter的基础使用(2)——线程的添加以及基本使用
  • 原文地址:https://www.cnblogs.com/topass123/p/12773507.html
Copyright © 2011-2022 走看看