二叉树到某一节点经过的路径

Posted topass123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树到某一节点经过的路径相关的知识,希望对你有一定的参考价值。

技术图片

 

 

# 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
        

 

以上是关于二叉树到某一节点经过的路径的主要内容,如果未能解决你的问题,请参考以下文章

剑指 Offer 34. 二叉树中和为某一值的路径附完整可运行代码

二叉树中和为某一值的路径

二叉树中和为某一值的路径

二叉树的和为某一条路径

二叉树中和为某一值的路径

二叉树中和为某一值的路径