Embercode
✕
Binary TreesQuick quiz

Maximum path sum

6 questions. Covers Maximum path sum with negative values in Python.

Questions 1 to 5 of 6

  1. 1. Why does best start at negative infinity (float('-inf')) and not at 0?
  2. 2. What does gain return to its parent?
  3. 3. What does this program print? ``python class TreeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right best = float('-inf') def max_path_sum(root): global best best = float('-inf') gain(root) return best def gain(node): global best if node is None: return 0 left = max(0, gain(node.left)) right = max(0, gain(node.right)) through = node.value + left + right best = max(best, through) return node.value + max(left, right) root = TreeNode(2, TreeNode(-1, TreeNode(5)), TreeNode(3)) print(max_path_sum(root)) ``
  4. 4. What does this program print? ``python class TreeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right best = float('-inf') def gain_no_clip(node): global best if node is None: return 0 left = gain_no_clip(node.left) right = gain_no_clip(node.right) through = node.value + left + right best = max(best, through) return node.value + max(left, right) root = TreeNode(3, TreeNode(-4), TreeNode(1)) gain_no_clip(root) print(best) ``
  5. 5. True or false: a child whose gain is -5 is clipped to 0, so its parent leaves that branch out of the path. Give the reason.

5 question(s) left on this page.