python7.4.2 binary tree routing problem and resolve LeetCode topic

  Following the path of the title, has extended the definition, some idea of ​​solution and challenges in time and space complexity.

  437. Path Sum III

  You are given a binary tree in which each node contains an integer value.

  Find the number of paths that sum to a given value.

  The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

  The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

  Example:

  root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

  10

  / \

  5 -3

  / \ \

  3 2 11

  / \ \

  3 -2 1

  Return 3. The paths that sum to 8 are:

  1. 5 -> 3

  2. 5 -> 2 -> 1

  3. -3 -> 11

  Topic Analysis:

  This problem extends the path to a node to route any of its descendants nodes, a solution, rate of nearly 1s, very slow, but the simple wording, the idea is the most direct approach, this pre-order traversing the tree, calling dfs function, find a path from the node until any sub-node, and whether the sum. The reasons for the low effect of the method is a lot of repeat traversal.

  class Solution:

  def pathSum(self, root: TreeNode, sum: int) -> int:

  """

  :type root: TreeNode

  :type sum: int

  :rtype: int

  """

  def dfs(node, sum):

  return dfs(node.left, sum-node.val) + dfs(node.right, sum-node.val) + (sum == node.val) if node else 0

  return dfs(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum) if root else 0

  Method two, after the frame for traversing the non-recursive, stack stores all parent nodes, sums stored list is any one as a starting node and a path (somewhat similar dynamic programming?), And thus the length of the stack consistent sums , and when any number is equal to the sum sums, a route request is satisfied. During the traversing, the nodes de-stacked, the corresponding sums also de-stacked, and each digital value obtained by subtracting the node. The method rate 500ms, but the spatial complexity is substantially top, beat 99.9%.

  class Solution:

  def pathSum(self, root: TreeNode, sum: int) -> int:

  if not root:

  return 0

  stack = []

  sums = []

  f = 0

  res = 0

  p = root

  while True:

  while p:

  stack.append(p)

  sums.append(0)

  for i in range(len(sums)):

  sums[i] += p.val

  if sums[i] == sum:

  res += 1

  p = p.left

  pre = None

  f = 1

  while stack and f:

  p = stack[-1]

  if p.right == pre:

  sums.pop()

  for i in range(len(sums)):

  sums[i] -= p.val

  stack.pop()

  for p =

  else:

  p = p.right

  f = 0

  if not stack:

  break

  return res

  The apparent complexity of the time, there are many optimization space, we see the new three big brothers do, 52ms, can be quite it. Carefully try to figure out the big ideas, above a solution is still to traverse only once, to avoid duplication, and therefore needs to be stored and the path has appeared, this solution introduces a hashmap. I approach slowly in value sums of the list, you need to subtract one by one in order to maintain its role, and the same sumMap action by key operation of the dictionary to solve performance problems. Rewrite some reference framework of this idea can be non-recursive above.

  class Solution:

  def pathSum(self, root: TreeNode, sum: int) -> int:

  """

  :type root: TreeNode

  :type sum: int

  :rtype: int

  """

  from collections import defaultdict

  def helper(cur, sumSoFar):

  nonlocal res, sumMap

  sumSoFar += cur.val

  if sumSoFar == sum:

  res + = 1 Wuxi gynecological hospital http://www.ytsg120.cn

  res += sumMap[sumSoFar - sum]

  sumMap[sumSoFar] += 1

  if cur.left:

  helper(cur.left, sumSoFar)

  if cur.right:

  helper(cur.right, sumSoFar)

  sumMap[sumSoFar] -= 1

  if not root:

  return 0

  sumMap = defaultdict(int)

  res = 0 if root.val != sum else 1

  sumMap[root.val] = 1

  if root.left:

  helper(root.left, root.val)

  if root.right:

  helper(root.right, root.val)

  return res

  124. Binary Tree Maximum Path Sum

  Given a non-empty binary tree, find the maximum path sum.

  For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

  Example 1:

  Input: [1,2,3]

  1

  / \

  2 3

  Output: 6

  Example 2:

  Input: [-10,9,20,null,null,15,7]

  -10

  / \

  9 20

  / \

  15 7

  Output: 42

  Topic Analysis:

  This question, in my opinion, seems to be the path to the title of the big boss. Topic baffled, finally I saw other people's writing, on her own a lot, in fact, different from the other path problem. We look at the code.

  class Solution:

  def maxPathSum(self, root: TreeNode) -> int:

  max_sum = float("-inf")

  def helper(node):

  nonlocal max_sum

  if not node:

  return 0

  lt_sum = helper(node.left)

  rt_sum = helper(node.right)

  local_sum = max(node.val, max(lt_sum, rt_sum) + node.val) # 1

  max_sum = max(max_sum, max(local_sum, lt_sum + rt_sum + node.val)) # 2

  return local_sum

  helper(root)

  return max_sum

  First, the subject is very different path, not necessarily including the leaf node, not necessarily including the root, there is likely to be left to the child to the right path to the parent of the child. The results of the subject, is a global variable; is a common problem solving process preorder traversal, recursive process accomplishes two things: First, the return local_sum, is the largest and the left or right subtree, the code determines that the node 1 the maximum value of its own, or combined with one of the left and right sub-tree and maximum (only choose one), the local value of the recursion direction corresponds at issue and request the path, the big problem is decomposed into such a small problem to solve; second thing is updated max_sum, this time allowing the node plus the value of the maximum left and right subtrees and form a complete path, it is determined to change the value is not the largest.


Guess you like

Origin blog.51cto.com/14335413/2426608