543. Diameter of Binary Tree (Easy)
https://leetcode.com/problems/diameter-of-binary-tree/
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.
Solutions
/**
* 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) {
// track keeps the depth of longest children branches for each node
Map<TreeNode, Integer> track = new HashMap<>();
recurse(root, 1, track);
int ans = 0;
for (TreeNode node : track.keySet()) {
ans = Math.max(track.get(node), ans);
}
// depth == edge, so return depth directly
return ans;
}
private int recurse(TreeNode root, int depth, Map<TreeNode, Integer> track) {
// root is null means for current path, the longest depth is depth - 1
if (root == null) {
return depth - 1;
}
// depth of left branch
int ld = recurse(root.left, depth + 1, track);
// depth of right branch
int rd = recurse(root.right, depth + 1, track);
// For each node, the diameter is the sum of left + right branches.
track.put(root, ld - depth + rd - depth);
// return the max length branch as the longest child branch of parent branch
return Math.max(ld, rd);
}
}