112. The sum of the path 113. Path sum II, 437. Total Path III

112. The sum of the path - and if a path exists = target

1 idea : Adapted from 113 title

class Solution:
    def hasPathSum(self, root: TreeNode, sumv: int) -> bool:
        ans,path = [],[]
        def helper(node):
            if not node: return
            path.append(node.val)
            if not node.left and not node.right:
                if sum(path)==sumv: ans.append(1)
            helper(node.left)
            helper(node.right)
            path.pop(-1)
        helper(root)
        return True if ans else False

Here Insert Picture Description
Simple version :

class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        if not root: return False
        if (not root.left and not root.right)and root.val==sum:return True
        return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)

Here Insert Picture Description
3 ideas : Order before non-recursive


class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        # 前序非递归 
        if not root:return False
        stack=[(root,sum)]
        while stack:
            node,sumval = stack.pop()
            if (not node.left) and (not node.right)and (node.val== sumval):return True
            if node.right:stack.append((node.right,sumval-node.val))
            if node.left:stack.append((node.left,sumval-node.val))
            sum+=node.val
        return False

And the sum of the path 113. The path II- = target path is given

1 idea : backtracking.
Depth recursive traversal, path determination, and, upon exiting back, remove the value of the path encountered when the leaf node.
Note: ans.append (path [:] Be sure to copy rather than the application, and shift a long time, and forget about it.
Time complexity: O (n)
complexity of space: O (n)

class Solution:
    def pathSum(self, root: TreeNode, sumv: int) -> List[List[int]]:
        ans,path = [],[]
        def helper(node):
            if not node: return
            path.append(node.val)
            if not node.left and not node.right:
                if sum(path)==sumv: ans.append(path[:])  # 注意
            helper(node.left)
            helper(node.right)
            path.pop(-1)
        helper(root)
        return ans

Here Insert Picture Description

The sum of the total number of paths path 437. III- (including sub-paths)

Given a binary tree, each node that are stored with an integer value.
Total number of paths to find the path and is equal to the given value.
Path does not require starting from the root, do not need to end in a leaf node, but the path direction must be down (only node from parent to child node).
Reference Solution: straightforward method of
thinking 1 : 113 based on the sub-path problems, checking each qualified path, coming this time complexity O (n- . 3 ), is certainly out.
2 ideas : to be seen as the root node of each node, the total number of operations required to perform the path. The time complexity is O (n- 2 )
corresponds to a recursive recursively nested inside.

class Solution:
    def pathSum(self, root: TreeNode, sumv: int) -> int:
        # 对于每个节点,都计算符合sum的路径数目
        if not root:return 0
        s= self.count(root,sumv)
        return s+self.pathSum(root.left,sumv)+self.pathSum(root.right,sumv)

    def count(self,node,sumval): 
        # 计算以当前节点为根,符合目标值的路径数目
        if not node:return 0
        s=1 if node.val == sumval else 0
        newsum = sumval-node.val
        return s+self.count(node.left,newsum)+self.count(node.right,newsum)

Here Insert Picture Description
3 ideas :
the need to fully grasp
how to achieve the next iteration?
-> requires access to a node when the number of sub-paths can be determined which meet the conditions
-> sum (abc) -sum ( ab) = target => sum (bc) = target sub path can be judged that the non-root nodes starting and
-> to continually move the end, we can determine sub-paths and different start and end points

class Solution(object):
    def pathSum(self, root, sum):
        def helper(node,target,pathsum,sumdic):
            if not node:return 0
            result = 0 # 当前节点为终点的路径存在的所有符合数目
            pathsum+=node.val # 新的以根节点为起点的路径和
            if pathsum==target: result+=1 # 符合 路径数+1
            result += sumdic.get(pathsum-target,0) # 符合的以非根节点为起点的路径和数目
            sumdic[pathsum] = sumdic.get(pathsum,0)+1 # 增加路径和对应的数目
            result += helper(node.left,target,pathsum,sumdic)
            result += helper(node.right,target,pathsum,sumdic)
            sumdic[pathsum]-=1  # 减少路径和对应的数目
            return result

        return helper(root,sum,0,{})

Here Insert Picture Description

Published 115 original articles · won praise 4 · Views 5021

Guess you like

Origin blog.csdn.net/qq_27921205/article/details/104306821