Maximum Average Subtree in Python

PythonServer Side ProgrammingProgramming

Suppose we have the root of a binary tree; we have to find the maximum average value of any subtree of that tree. So if the tree is like −

The output will be 6, this is because, for node 5, it will be (5 + 6 + 1)/ 3 = 4, then for node 6 it will be 6 / 1 = 6, and for node 1, it will be 1 / 1 = 1, so the max is 6.

To solve this, we will follow these steps −

  • res := 0

  • Define a method called solve(), this will take root

  • if root is not set, then return a pair [0, 0]

  • left := solve(left of root) right := solve(right of root)

  • c := left[0] + right[0] + 1

  • s := left[1] + right[1] + value of root

  • ans := max of and ans s/c

  • return a pair[c, s]

  • From the main method, set ans := 0, call solve(root) and return ans

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def brokenCalc(self, X, Y):
      """
      :type X: int
      :type Y: int
      :rtype: int
      """
      res = 0
      while Y > X:
         res += Y % 2 + 1
         Y = Y // 2 if Y % 2 == 0 else (Y + 1)//2
      return res + X - Y

Input

5
8

Output

2
raja
Published on 17-Mar-2020 06:52:04
Advertisements