diameter-of-binary-tree
Problem
Problem Description
Solution
From problem description, longest path mah or may not pass through the root.
For example:
The idea is to calculate the longest path from left subtree, and right subtree, and record longest path (left, right, (left + right)).
Using helper class Depth to record each node depth and max diameter. This way we can optimize the time complexity to O(n)
.
Recursively find the height of left subtree
Recursively find the height of right subtree
Calculate max diameter max(left diameter, right diameter, (left.height + right.height))
Return max depth and max diameter.
Complexity Analysis
Time Complexity: O(n)
n - number of tree nodes.
Code
Last updated