二叉树与分治法整理
Posted yunyouhua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树与分治法整理相关的知识,希望对你有一定的参考价值。
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 }
①计算sum时每层+1②忘记helper返回值。
答案可以更简单一点。
1 if (subtree == null || 2 subtreeResult.sum * result.size < result.sum * subtreeResult.size 3 ) { 4 subtree = root; 5 subtreeResult = result; 6 }
以上是关于二叉树与分治法整理的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode之分治法专题-654. 最大二叉树(Maximum Binary Tree)
二叉树有关习题整理145二叉树的后序遍历 94二叉树的中序遍历 572另一棵树的子树 236二叉树的最近公共祖先 JZ36二叉搜索树与双向链表 - 牛客