543. Diameter of Binary Tree
来源:互联网 发布:达达抢单软件靠谱吗 编辑:程序博客网 时间:2024/06/06 01:58
思路:利用分治法,得到每个节点的左子树的最大深度,再得到每个节点的右子树的最大深度,那么此节点的最大直径即为left+right(不为left+right+1)。
预先定义好一个最大直径值max,在遍历每个节点的时候,都与这个max做比较。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { private int max = 0; public int diameterOfBinaryTree(TreeNode root) { maxDepth(root); return max; } private int maxDepth(TreeNode root){ if (root == null){ return 0; } int left = maxDepth(root.left); int right = maxDepth(root.right); max = Math.max(max, left + right); return Math.max(left, right) + 1; }}
阅读全文
0 0
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- Diameter of Binary Tree
- spring框架详解(一)--IOC与注入
- mysql--存储过程
- PHP 常用的header头部定义汇总
- asp.net 苹果设备无法登陆问题
- 五步教你设计成功而有价值的数据可视化
- 543. Diameter of Binary Tree
- Oracle 11G RAC数据库安装
- 利用手机的GPS获取经纬度
- FineCMS安装教程
- Activiti进阶(三)——流程定义的CRUD
- IntelliJ IDEA 常用快捷键
- va_list 与print
- display:inline、block、inline-block的区别
- jdk的安装以及环境变量配置