zoukankan      html  css  js  c++  java
  • [LintCode] 597 Subtree with Maximum Average 解题报告

    Description
    Given a binary tree, find the subtree with maximum average. Return the root of the subtree.

    Notice
    LintCode will print the subtree which root is your return node.
    It's guaranteed that there is only one subtree with maximum average.


    Example
    Given a binary tree:

         1
        /  
     -5     11
     /     /  
    1   2 4    -2

    return the node 11.

    5/8/2017

    算法班

    未经测试

     1 public class Solution {
     2     /**
     3      * @param root the root of binary tree
     4      * @return the root of the maximum average of subtree
     5      */
     6     
     7     class Result {
     8         int sum;
     9         int size;
    10         TreeNode root;
    11         Result(TreeNode root, int sum, int size) {
    12             this.root = root;
    13             this.sum = sum;
    14             this.size = size;
    15         }
    16     }
    17 
    18     private Result subtree = null;
    19 
    20     public TreeNode findSubtree2(TreeNode root) {
    21         if (root == null) return null;
    22         Result _ = getMaxAverage(root);
    23         return subtree.root;
    24     }
    25     private Result getMaxAverage(TreeNode root) {
    26         if (root.left == null && root.right == null) {
    27             Result ret = new Result(root, root.val, 1);
    28             if (subtree == null || subtree.sum < root.val * subtree.size) {
    29                 subtree = ret;
    30             }
    31             return ret;
    32         }
    33         Result left = root.left == null ? null: getMaxAverage(root.left);
    34         Result right = root.right == null ? null: getMaxAverage(root.right);
    35         Result current = new Result(root, root.val + left == null? 0: left.sum + right == null? 0: right.sum, 1 + left == null? 0: left.size + right == null? 0: right.size);
    36         if (subtree == null || current.sum * subtree.size > subtree.sum * current.size) {
    37             subtree = current;
    38         }
    39         return current;
    40     }
    41 }

    九章解法

    https://www.jiuzhang.com/solutions/subtree-with-maximum-average/

  • 相关阅读:
    TCMalloc 内存分配原理简析
    技术人沟通中的几个常见问题
    不同路径
    Js将字符串转数字的方式
    防抖节流模式
    Location对象
    React生命周期
    fgrep命令
    数据访问对象模式
    保持城市天际线
  • 原文地址:https://www.cnblogs.com/panini/p/6828755.html
Copyright © 2011-2022 走看看