题目中的直径定义为:
任意两个节点的最远距离
没想出来,看的答案
思路是:diameter = max(左子树diameter,右子树diameter,(左子树深度+右子树深度+1))
遍历并更新结果
int res = 1; public int diameterOfBinaryTree(TreeNode root) { helper(root); return res-1; } public int[] helper(TreeNode root) { //两个量分别是节点深度,节点最大diameter if (root==null) return new int[]{0,0}; int cur = 0; int[] l = helper(root.left); int[] r = helper(root.right); cur = Math.max(Math.max(l[1],r[1]),l[0]+r[0]+1); res = Math.max(res,cur); return new int[]{Math.max(l[0],r[0])+1,cur}; }