Time complexity to find the diameter of a binary tree having n nodes is
- (A)
O(n^2)
- (B)
O(n)
- (C)
O(1)
- (D)
O(log n)
Time complexity to find the diameter of a binary tree having n nodes is
O(n^2)
O(n)
O(1)
O(log n)
ANSWER
The diameter of a binary tree with nodes can be found in time, option (b). Option (a), , is the naive method and is also a correct upper bound.
Official answer: A or BSource: ISRO's revised and final answer key of 16 February 2024
The diameter of a binary tree is the number of nodes (or edges) on the longest path between any two nodes. That path need not pass through the root.
For each node , the longest path whose topmost node is has nodes. The diameter is the maximum of this value over all nodes.
The naive method computes the heights of both subtrees separately at every node. Each height computation costs , so the total is in the worst case, for example a skewed tree.
The better method does one post-order traversal. Each call returns the height of its subtree and updates a running maximum diameter using the children's heights. A node's height follows from its children's heights in .
Every node is visited once and does work, so , which solves to .
A lower bound of also holds, because any node could lie on the longest path, so every node must be examined. Hence the tight bound is , which is option (b).
Option (a), , is the cost of the naive method and is also a valid upper bound, since , but it is not tight. Options (c) and (d) are impossible, because even reading all the nodes takes .
KEY IDEA
Compute subtree heights and the best path through each node in a single post-order traversal, so each node is handled once in constant time.
WATCH OUT FOR
Recomputing the height of both subtrees at every node, which gives on a skewed tree, or assuming the longest path must pass through the root.
From the ISRO CS 2023 paper. Every question of this paper · The full paper (PDF, ISRO) · All 3 ISRO Trees & heaps questions, with notes