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
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));
}
}