Leetcode 543. Diameter of Binary Tree
The problem statement for “Diameter of Binary Tree” on LeetCode is as follows:
Given the root
of a binary tree, return 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.
The length of a path between two nodes is represented by the number of edges between them.
Before we dive into the solution, let’s clarify a few things:
To solve the problem, we can use a depth-first search (DFS) approach. The idea is to:
height(node)
:
null
, return 0.#include <algorithm> // for max
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int diameter = 0; // Global variable to store the diameter
height(root, diameter);
return diameter;
}
private:
int height(TreeNode* node, int& diameter) {
if (node == nullptr) return 0;
int leftHeight = height(node->left, diameter);
int rightHeight = height(node->right, diameter);
// Update the diameter
diameter = std::max(diameter, leftHeight + rightHeight);
// Return the height of the tree
return std::max(leftHeight, rightHeight) + 1;
}
};
The time complexity of this solution is O(N), where N is the number of nodes in the binary tree. This is because we traverse each node exactly once during the depth-first search to compute the heights and simultaneously update the diameter.
The space complexity is O(H), where H is the height of the binary tree. This accounts for the recursive stack space used during the depth-first search. In the worst case (skewed tree), the height can be N
, making the space complexity O(N). In the average case, for a balanced tree, it would be O(log N).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?