0
0
DSA Goprogramming~5 mins

Diameter of Binary Tree in DSA Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Diameter of Binary Tree
O(n)
Understanding Time Complexity

We want to understand how the time needed to find the diameter of a binary tree changes as the tree grows.

The question is: how does the number of steps grow when the tree has more nodes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func diameterOfBinaryTree(root *TreeNode) int {
    maxDiameter := 0
    var depth func(node *TreeNode) int
    depth = func(node *TreeNode) int {
        if node == nil {
            return 0
        }
        left := depth(node.Left)
        right := depth(node.Right)
        if left+right > maxDiameter {
            maxDiameter = left + right
        }
        if left > right {
            return left + 1
        }
        return right + 1
    }
    depth(root)
    return maxDiameter
}
    

This code finds the longest path between any two nodes in a binary tree by calculating depths recursively.

Identify Repeating Operations
  • Primary operation: Recursive calls to visit each node once.
  • How many times: Each node is visited exactly one time.
How Execution Grows With Input

As the number of nodes (n) increases, the function visits each node once to calculate depths.

Input Size (n)Approx. Operations
10About 10 recursive calls
100About 100 recursive calls
1000About 1000 recursive calls

Pattern observation: The number of operations grows roughly in direct proportion to the number of nodes.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the diameter grows linearly with the number of nodes in the tree.

Common Mistake

[X] Wrong: "The function visits nodes multiple times, so time is more than linear."

[OK] Correct: Each node is visited once during the depth calculation, so the total work is proportional to the number of nodes.

Interview Connect

Understanding this linear time complexity helps you explain efficient tree traversal and recursion in interviews confidently.

Self-Check

"What if the tree was skewed (like a linked list)? How would the time complexity change?"