码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树与分治法整理

时间:2017-11-23 10:57:15      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:分治法   col   close   code   type   src   style   tree   find   

597. 具有最大平均数的子树

技术分享图片
 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param root: the root of binary tree
17      * @return: the root of the maximum average of subtree
18      */
19     class Type {
20         int sum;
21         int count;
22         Type(int s, int c) {
23             sum = s;
24             count = c;
25         }
26     }
27     TreeNode res = null;
28     Type max = new Type(0, 0);
29     public TreeNode findSubtree2(TreeNode root) {
30         // write your code here
31         helper(root);
32         return res;
33     }
34     //1. 对于root,返回该节点为根节点的count和sum
35     private Type helper(TreeNode root) {
36         if (root == null) {
37             return new Type(0, 0);
38         }
39         
40         //2.拆解
41         Type left = helper(root.left);
42         Type right = helper(root.right);
43         int sum = left.sum + right.sum + root.val;
44         int count = left.count + right.count + 1; //+1手误
45         if (res == null || sum * max.count > max.sum * count) {
46             max.count = count;
47             max.sum = sum;
48             res = root;
49         }
50         return new Type(sum, count); //忘记了
51     }
52 }
View Code

①计算sum时每层+1②忘记helper返回值。

答案可以更简单一点。

技术分享图片
1 if (subtree == null ||
2             subtreeResult.sum * result.size < result.sum * subtreeResult.size
3         ) {
4             subtree = root;
5             subtreeResult = result;
6         }
View Code

 

二叉树与分治法整理

标签:分治法   col   close   code   type   src   style   tree   find   

原文地址:http://www.cnblogs.com/yunyouhua/p/7883265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!