543. Diameter of Binary Tree
来源:互联网 发布:剑网3莫雨捏脸数据 编辑:程序博客网 时间:2024/05/17 20:34
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].
Note: The length of path between two nodes is represented by the number of edges between them.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { 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); //在这里更新max 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
- 用python写一个小型的FTP客户端软件
- java学习(22)--JDBC(二)
- SpringMVC原理
- Leetcode 14. Longest Common Prefix
- 【脚本语言系列】关于Python进程线程管理系统模块,你需要知道的事
- 543. Diameter of Binary Tree
- windows 64位下安装scipy(python2.7)
- 【Android 清单文件下的 Activity各种配置详解】
- RML(Riemann流形学习)
- 实测:一周不更新文章头条号指数会掉多少?
- POJ 1290 Grandpa's Rubik Cube 笔记
- Js作用域与作用域链详解
- 如何在官网下载Spring各个版本的jar包
- Android绘制机制Paint基础学习