Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Maximum Average Subtree

Posted on July 22, 2019July 26, 2020 by braindenny

Maximum Average Subtree



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #postorder

Given the root of a binary tree, find the maximum average value of any subtree of that tree.

(A subtree of a tree is any node of that tree plus all its descendants. The average value of a tree is the sum of its values, divided by the number of nodes.)

Example 1:

Leetcode: Maximum Average Subtree

Input: [5,6,1]
Output: 6.00000
Explanation: 
For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4.
For the node with value = 6 we have an average of 6 / 1 = 6.
For the node with value = 1 we have an average of 1 / 1 = 1.
So the answer is 6 which is the maximum.

Note:

  1. The number of nodes in the tree is between 1 and 5000.
  2. Each node will have a value between 0 and 100000.
  3. Answers will be accepted as correct if they are within 10^-5 of the correct answer.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// https://code.dennyzhang.com/maximum-average-subtree
// Basic Ideas: dfs + post-order
// Complexity: Time O(n), Space O(1)
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func dfs(root *TreeNode, max *float64) (sum int, cnt int) {
    if root == nil { return 0, 0 }
    lsum, lcnt := dfs(root.Left, max)
    rsum, rcnt := dfs(root.Right, max)
    sum, cnt = lsum + rsum + root.Val, lcnt + rcnt + 1
    val := float64(sum)/float64(cnt)
    if val > *max { *max = val }
    return
}

func maximumAverageSubtree(root *TreeNode) float64 {
    res := float64(0)
    dfs(root, &res)
    return res
}
linkedin
github
slack

Post Views: 0
Posted in BasicTagged #dfs, postorder

Post navigation

LeetCode: Number of Days in a Month
LeetCode: Snapshot Array

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.