Dsa
Trees
Medium
Max Depth of Tree with Parent Pointers
You are given a binary tree where each node has a pointer to its parent. Implement a function that calculates the maximum depth of the tree. The depth of a node is defined as the number of edges on the longest downward path from that node to a leaf.
Input format:
The input starts with an integer n (1 <= n <= 1000), the number of nodes in the tree. Then n lines follow, each containing the value of the node and the value of its parent. If a node does not have a parent (it is the root), the parent value will be -1.
Output format:
Print a single integer representing the maximum depth of the tree.
Example:
Input:
5
1 -1
2 1
3 1
4 2
5 2
Output:
2
Key concepts
treesdepthparent pointers
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now