标签:分治法 col close code type src style tree find
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 }
①计算sum时每层+1②忘记helper返回值。
答案可以更简单一点。
1 if (subtree == null || 2 subtreeResult.sum * result.size < result.sum * subtreeResult.size 3 ) { 4 subtree = root; 5 subtreeResult = result; 6 }
标签:分治法 col close code type src style tree find
原文地址:http://www.cnblogs.com/yunyouhua/p/7883265.html