Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
93 views
in Information Technology by (178k points)
What is the time complexity of the provided code?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

The provided code calculates the diameter of a binary tree using a recursive approach. Let's analyze the time complexity of the code:

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def tree_diameter(root):
    if root is None:
        return 0

    # Recursively calculate heights of left and right subtrees
    height_left = calculate_height(root.left)
    height_right = calculate_height(root.right)

    # Calculate diameter using the recursive formula
    diameter = max(tree_diameter(root.left),
                   tree_diameter(root.right),
                   height_left + height_right + 1)

    return diameter

def calculate_height(node):
    if node is None:
        return 0
    return max(calculate_height(node.left), calculate_height(node.right)) + 1
 

Let N be the number of nodes in the binary tree.

  1. Calculating Heights:

    • The calculate_height function is called for each node in the tree, and it traverses each node once. The time complexity of calculating the height of the tree is O(N).
  2. Calculating Diameter:

    • The tree_diameter function recursively calculates the heights and the diameter. For each node, it calculates the heights and the diameter using constant-time operations. The function traverses each node once, and the total work done for each node is a constant multiple of the height calculation.
    • The recursive calls form a binary tree structure, and each node is processed once. Therefore, the time complexity of calculating the diameter is also O(N).

The overall time complexity of the provided code is O(N), where N is the number of nodes in the binary tree.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...