Diameter of Binary Tree
Given the root
of a binary tree, return the diameter of the binary 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.
The length of a path between two nodes is represented by the number of edges between them.
Solution
Use a recursive function to calculate the height of the tree. The function will return the maximum depth of the left and right child nodes, and then return the maximum of the two plus one. While calculating the height, we can also calculate the diameter of the tree by adding the height of the left and right child nodes.
Implementation
Pseudocode
- If the root is
None
, return 0. - Calculate the height of the left and right child nodes recursively.
- Update the diameter of the tree by adding the height of the left and right child nodes.
- Return the maximum of the height of the left and right child nodes plus one.
Complexity Analysis
- Time complexity: O(n) - because we visit each node exactly once.
- Space complexity: O(n) due to the recursive call stack.