Bird
Raised Fist0
DSA Pythonprogramming~20 mins

Diameter of Binary Tree in DSA Python - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Diameter Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of diameter calculation on a simple binary tree
What is the output of the following code that calculates the diameter of a binary tree?
DSA Python
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def diameter(root):
    diameter_result = [0]
    def depth(node):
        if not node:
            return 0
        left = depth(node.left)
        right = depth(node.right)
        diameter_result[0] = max(diameter_result[0], left + right)
        return 1 + max(left, right)
    depth(root)
    return diameter_result[0]

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print(diameter(root))
A5
B2
C4
D3
Attempts:
2 left
💡 Hint
Think about the longest path between any two nodes in the tree.
🧠 Conceptual
intermediate
1:30remaining
Understanding diameter definition in binary trees
Which of the following best describes the diameter of a binary tree?
AThe number of edges on the longest path between any two nodes in the tree.
BThe height of the tree plus one.
CThe number of leaf nodes in the tree.
DThe number of nodes on the longest path between any two nodes in the tree.
Attempts:
2 left
💡 Hint
Diameter counts edges, not nodes.
🔧 Debug
advanced
2:00remaining
Identify the error in diameter calculation code
What error will the following code produce when calculating the diameter of a binary tree?
DSA Python
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def diameter(root):
    max_diameter = 0
    def depth(node):
        if not node:
            return 0
        left = depth(node.left)
        right = depth(node.right)
        nonlocal max_diameter
        max_diameter = max(max_diameter, left + right)
        return 1 + max(left, right)
    depth(root)
    return max_diameter

root = Node(1)
root.left = Node(2)
root.right = Node(3)
print(diameter(root))
ANameError: name 'max_diameter' is not defined
BThe function returns 0 instead of the correct diameter
CTypeError due to incorrect max function usage
DRecursionError due to infinite recursion
Attempts:
2 left
💡 Hint
Check variable scope inside nested functions.
🚀 Application
advanced
2:30remaining
Diameter of unbalanced binary tree
Given the following unbalanced binary tree, what is the diameter?
DSA Python
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

root = Node(1)
root.left = Node(2)
root.left.left = Node(3)
root.left.left.left = Node(4)
root.right = Node(5)
root.right.right = Node(6)
root.right.right.right = Node(7)

# Diameter function as defined previously

def diameter(root):
    diameter_result = [0]
    def depth(node):
        if not node:
            return 0
        left = depth(node.left)
        right = depth(node.right)
        diameter_result[0] = max(diameter_result[0], left + right)
        return 1 + max(left, right)
    depth(root)
    return diameter_result[0]

print(diameter(root))
A6
B5
C4
D7
Attempts:
2 left
💡 Hint
Consider the longest path between leaf nodes across the root.
🧠 Conceptual
expert
1:30remaining
Time complexity of diameter calculation using single traversal
What is the time complexity of calculating the diameter of a binary tree using a single traversal approach that computes depth and updates diameter simultaneously?
AO(n^2), because depth is calculated for each node separately
BO(log n), assuming the tree is balanced
CO(n), where n is the number of nodes in the tree
DO(1), since diameter is computed during traversal
Attempts:
2 left
💡 Hint
Each node is visited once in the single traversal method.

Practice

(1/5)
1. What does the diameter of a binary tree represent?
easy
A. The length of the longest path between any two nodes in the tree
B. The number of nodes in the tree
C. The height of the tree
D. The number of leaf nodes

Solution

  1. Step 1: Understand the diameter definition

    The diameter is the longest path between any two nodes, not just from root to leaf.
  2. Step 2: Differentiate from height and node count

    Height is longest root-to-leaf path; node count is total nodes; diameter can be longer than height.
  3. Final Answer:

    The length of the longest path between any two nodes in the tree -> Option A
  4. Quick Check:

    Diameter = longest path length [OK]
Hint: Diameter is longest path between any two nodes, not just height [OK]
Common Mistakes:
  • Confusing diameter with height
  • Thinking diameter counts nodes instead of edges
  • Assuming diameter is always root to leaf
2. Which of the following Python function signatures is correct for computing the diameter of a binary tree node?
easy
A. def diameter(root: int) -> TreeNode:
B. def diameter(root: Optional[TreeNode]) -> int:
C. def diameter(root: TreeNode) -> str:
D. def diameter(root: List[int]) -> int:

Solution

  1. Step 1: Identify correct parameter and return types

    Function takes a tree node or None and returns an integer diameter length.
  2. Step 2: Check each option's signature

    def diameter(root: Optional[TreeNode]) -> int: matches expected input (node or None) and output (int). Others mismatch types.
  3. Final Answer:

    def diameter(root: Optional[TreeNode]) -> int: -> Option B
  4. Quick Check:

    Input node, output int diameter [OK]
Hint: Diameter function inputs root node, returns int length [OK]
Common Mistakes:
  • Using wrong input type like int or list
  • Returning wrong type like str or TreeNode
  • Missing Optional for nullable root
3. What is the output of the following code snippet?
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def diameter(root):
    diameter_val = 0
    def depth(node):
        nonlocal diameter_val
        if not node:
            return 0
        left = depth(node.left)
        right = depth(node.right)
        diameter_val = max(diameter_val, left + right)
        return max(left, right) + 1
    depth(root)
    return diameter_val

root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
print(diameter(root))
medium
A. 2
B. 4
C. 3
D. 5

Solution

  1. Step 1: Understand tree structure and depth calls

    Tree has root 1, left subtree with nodes 2,4,5 and right subtree with node 3. Longest path is 4->2->1->3 or 5->2->1->3 with length 3 edges.
  2. Step 2: Calculate diameter_val during recursion

    At node 2, left and right depths are 1 each, sum 2; at root, left depth 2, right depth 1, sum 3 updates diameter_val to 3.
  3. Final Answer:

    3 -> Option C
  4. Quick Check:

    Longest path edges = 3 [OK]
Hint: Diameter counts edges on longest path, not nodes [OK]
Common Mistakes:
  • Counting nodes instead of edges for diameter
  • Ignoring nonlocal update of diameter_val
  • Misunderstanding tree structure
4. Find the error in the following diameter function and select the fix:
def diameter(root):
    diameter_val = 0
    def depth(node):
        if not node:
            return 0
        left = depth(node.left)
        right = depth(node.right)
        diameter_val = max(diameter_val, left + right)
        return max(left, right) + 1
    depth(root)
    return diameter_val
medium
A. Initialize diameter_val inside depth() function
B. Change 'diameter_val' to a global variable
C. Return diameter_val inside depth() function
D. Add 'nonlocal diameter_val' inside depth() to update outer variable

Solution

  1. Step 1: Identify variable scope issue

    diameter_val is assigned inside depth() but not declared nonlocal, so assignment creates local variable, not updating outer diameter_val.
  2. Step 2: Fix by declaring nonlocal

    Adding 'nonlocal diameter_val' inside depth() allows updating the outer variable correctly.
  3. Final Answer:

    Add 'nonlocal diameter_val' inside depth() to update outer variable -> Option D
  4. Quick Check:

    Use nonlocal to modify outer variable [OK]
Hint: Use nonlocal to update outer variable inside nested function [OK]
Common Mistakes:
  • Forgetting nonlocal causes no diameter update
  • Using global unnecessarily
  • Returning diameter_val inside depth() breaks logic
5. Given a binary tree where some nodes have only one child, how does the diameter calculation handle paths through these nodes? Choose the correct statement about the diameter in such cases.
hard
A. Diameter counts the longest path even if it passes through nodes with only one child
B. Diameter ignores nodes with only one child when calculating longest path
C. Diameter is always the height of the tree when nodes have one child
D. Diameter equals the number of leaf nodes in the tree

Solution

  1. Step 1: Understand diameter path definition

    Diameter is longest path between any two nodes, regardless of node children count.
  2. Step 2: Consider nodes with one child

    Paths can pass through nodes with one child; these nodes do not exclude paths from consideration.
  3. Final Answer:

    Diameter counts the longest path even if it passes through nodes with only one child -> Option A
  4. Quick Check:

    Diameter includes all nodes on longest path [OK]
Hint: Diameter includes all nodes on longest path, child count doesn't exclude [OK]
Common Mistakes:
  • Assuming nodes with one child are ignored
  • Confusing diameter with height in skewed trees
  • Thinking diameter equals leaf count
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard