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 longestpath 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.
Java Solution:
Runtime beats 72.26%
完成日期:06/30/2017
关键词:Tree
关键点:用post order去返回每一个点的depth(在之前depth值上+1),null点就返回0(base case);
需要两个function,因为getDepth function 返回的都是depth,不是diameter,所以需要diameterOfBinaryTree 来单独返回diameter;
每一个点的最大直径等于左边的depth 加上 右边的depth,取所有点中最大的值。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
int diameter = 0; public int diameterOfBinaryTree(TreeNode root)
{
getDepth(root); return diameter;
} public int getDepth(TreeNode root)
{
if(root == null)
return 0; int left = getDepth(root.left);
int right = getDepth(root.right); int temp = left + right; if(temp > diameter)
diameter = temp; return Math.max(left, right) + 1;
}
}
参考资料:
http://blog.csdn.net/zhouziyu2011/article/details/64123326
改动了一下,因为temp = left + right + 2 有点绕。返回0更直接易懂。