← TCS bank

TCS · Question 6 · Trees

Diameter of a Binary Tree

TreesC++code⏱ O(n)💾 O(h)
Service-based

Problem

Find the longest path between any two nodes in a tree.

Approach

Post-order heights; the diameter through a node is left + right height.

Time O(n)Space O(h)

How it works

  1. 1Height of a node is one plus its taller side.
  2. 2Diameter through it is the sum of both sides; keep the global max in edges.

Sample input / output

Input:
root = [1, 2, 3, 4, 5]
Output:
3

Constraints

1 <= nodes <= 10^4.

Solution — read it, then walk it

Time O(n)Space O(h)Loops 2Branches 4Returns 3source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeatSTARTinclude <iostream>include <vector>include <climits>include <algorithm>using namespace stdCLASS TreeNodeDEFINE valTreeNode *left, *rightTreeNode(int x) : val(x),left(nullptr),right(nullptr) {}TreeNode* buildTree(constvector<int>& vs, intnullMark = INT_MIN)DEFINE levelPrint(TreeNode*root)if (!root) { cout <<"[]" << endl; return;}vector<TreeNode*> q ={root}vector<int> outsize_t qi = 0while (qi < q.size())TreeNode* node = q[qi++]if (!node) continueout.push_back(node->val)q.push_back(node->left)q.push_back(node->right)cout << "["for (size_t i = 0; i <out.size(); ++i)if (i) cout << ", "cout << out[i]cout << "]" << endlDEFINE diameter = 0DEFINE height(TreeNode*root)if (!root) return 0DEFINE left =height(root->left)DEFINE right =height(root->right)diameter = max(diameter,left + right)RETURN 1 + max(left, right)DEFINEdiameterOfBinaryTree(TreeNode*root)diameter = 0height(root)RETURN diameterDEFINE main()cout <<diameterOfBinaryTree(buildTree({1,2, 3, 4, 5})) << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/41

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits