Prepin
Log in

Determine the height of a binary tree.

Approach / Explanation

In this question, you, as the candidate, are required to showcase your comprehension of a binary tree data structure and your capability to determine its height. A binary tree is a specific type of tree where each node can have no more than two children, commonly known as the left child and the right child. The height of a binary tree is characterized as the greatest depth among its nodes, with the depth of a node defined as the distance from that node to the root. A tree that consists of only one node (the root) is assigned a height of 0. To appropriately respond to this question, you should possess a foundational knowledge of computer science and data structures, along with proficiency in a programming language of your choice, as you will likely need to write a function to compute the height. Be ready to clarify each part of your response and to address any potential follow-up questions regarding the properties of tree data structures or the time and space complexity of your solution.

Suggested Answer

Below is an example of a Python function that determines the height of a binary tree: class Node : def __init__ ( self , value ) : self . value = value self . left = None self . right = None def height ( node ) : if node is None : return - 1 else : left_height = height ( node . left ) right_height = height ( node . right ) return 1 + max ( left_height , right_height ) This code begins by defining the Node class for the nodes in the binary tree, followed by the height function that computes the height of the tree. The function is designed as a recursive method that explores all paths in the binary tree, choosing the longest one and adding one to account for the root node.

Alternative Answer

Below is an example of a corresponding Java function: class Node { int value ; Node left , right ; Node ( int value ) { this . value = value ; left = right = null ; } } int height ( Node node ) { if ( node == null ) { return - 1 ; } else { int leftHeight = height ( node . left ) ; int rightHeight = height ( node . right ) ; return Math . max ( leftHeight , rightHeight ) + 1 ; } } This Java code performs a task similar to the earlier Python code, despite the difference in programming languages. The height method computes the height of the binary tree by recursively evaluating the height of each subtree and adding 1 for the root node.

Question Details

Difficulty & Category

Medium

Companies

Google

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.