Description
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
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.
Solution
DFS
以每个节点为起点,往左右两边扩展,更新diameter。
这里用到一个depth方法用作辅助,但是这个depth的定义跟惯用的定义不太一样,对于leaf节点depth是1,对于root节点则是root到最深leaf的距离+1。
这道题唯一要注意的就是值不要弄错了。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) {
return 0;
}
int path = depth(root.left) + depth(root.right);
int leftPath = diameterOfBinaryTree(root.left);
int rightPath = diameterOfBinaryTree(root.right);
return Math.max(path, Math.max(leftPath, rightPath));
}
public int depth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(depth(root.left), depth(root.right));
}
}