Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree

          1
/ \
2 3
/ \
4 5

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

题目

给定一棵二叉树,求任意两个节点的最长路径长度。

思路

长度的定义是边的个数,不是node的个数

跟 [leetcode]124. Binary Tree Maximum Path Sum二叉树最大路径和 思路一致。

代码

 class Solution {
public int diameterOfBinaryTree(TreeNode root) {
/* 要么用个global variable放在class下,要么用长度为1的一维数组来存。
这里因为求edge的数量,初始化为一维数组的default值0是可行的。
*/
int[] diameter = new int[1];
dfs(root, diameter);
return diameter[0];
} private int dfs(TreeNode node, int[] diameter) {
if(node == null){return 0;} int lh = dfs(node.left, diameter);
int rh = dfs(node.right, diameter); diameter[0] = Math.max(diameter[0], lh + rh);
return Math.max(lh, rh) + 1;
}
}

最新文章

  1. javascript 异步模块加载 简易实现
  2. 【五子棋AI循序渐进】——整合完成
  3. 【JSP&Servlet学习笔记】4.会话管理
  4. UVA10972 - RevolC FaeLoN(双连通分量)
  5. Java基础知识强化74:正则表达式之分割功能 (扩展练习)
  6. [HDU] 2063 过山车(二分图最大匹配)
  7. egret随笔-publish命令的改进
  8. 我在网站开发中经常用到的几个js函数01
  9. MongoDB基础教程系列--第九篇 MongoDB 分片
  10. Apt下载安装包时Hash校验和不符
  11. POJ - 2528 Mayor's posters (离散化+线段树区间修改)
  12. Geoserver GeoWebCache 切图失败 This requested used more time than allowed and has been forcefully stopped. Max rendering time is 60.0s
  13. 使用Java实现面向对象编程
  14. OpenStack 云主机深入了解(十四)
  15. Java:多线程,CyclicBarrier同步器
  16. 【LOJ】#2320. 「清华集训 2017」生成树计数
  17. codevs 1060 搞笑运动会 dp
  18. FrameWork数据权限浅析3之基于角色的配置表实现行级数据安全
  19. 卡诺模型(KANO Model)
  20. Nlog日志出坑合集

热门文章

  1. Eclipse中安装及配置EGit插件
  2. 长沙雅礼中学集训-------------------day1(内含day0)
  3. Samba 简介
  4. blktrace未公开选项网络保存截取数据
  5. 处理存在UNASSIGNED的主分片导致Elasticsearch集群状态为Red的问题
  6. js的sort(0实现数组的排序
  7. 在oracle下如何创建database link全面总结
  8. django-后台sms管理系统的css框架
  9. Ingress.yaml
  10. 0_Simple__simpleCubemapTexture