Bird
Raised Fist0
DSA Typescriptprogramming~20 mins

DP on Trees Diameter of Tree in DSA Typescript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Tree Diameter Master
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 tree
What is the output of the following TypeScript code that calculates the diameter of a tree using DP on trees?
DSA Typescript
type Tree = { [key: number]: number[] };

function treeDiameter(tree: Tree): number {
  let diameter = 0;

  function dfs(node: number, parent: number): number {
    let max1 = 0, max2 = 0;
    for (const child of tree[node] || []) {
      if (child === parent) continue;
      const depth = dfs(child, node);
      if (depth > max1) {
        max2 = max1;
        max1 = depth;
      } else if (depth > max2) {
        max2 = depth;
      }
    }
    diameter = Math.max(diameter, max1 + max2);
    return max1 + 1;
  }

  dfs(0, -1);
  return diameter;
}

const tree = {
  0: [1, 2],
  1: [0, 3, 4],
  2: [0],
  3: [1],
  4: [1]
};

console.log(treeDiameter(tree));
A2
B4
C3
D5
Attempts:
2 left
💡 Hint
Think about the longest path between any two nodes in the tree.
🧠 Conceptual
intermediate
1:30remaining
Understanding the role of DP in tree diameter calculation
Which statement best describes how dynamic programming (DP) is used in calculating the diameter of a tree?
ADP is used to count the total number of nodes in the tree.
BDP stores the longest path from each node to its descendants to avoid recomputation.
CDP helps in converting the tree into a binary tree for easier diameter calculation.
DDP is used to sort the nodes in the tree before calculating the diameter.
Attempts:
2 left
💡 Hint
Think about how repeated calculations are avoided in DFS.
🔧 Debug
advanced
2:00remaining
Identify the error in this diameter calculation code
What error will this TypeScript code produce when calculating the diameter of a tree?
DSA Typescript
type Tree = { [key: number]: number[] };

function treeDiameter(tree: Tree): number {
  let diameter = 0;

  function dfs(node: number, parent: number): number {
    let max1 = 0, max2 = 0;
    for (const child of tree[node] || []) {
      if (child === parent) continue;
      const depth = dfs(child, node);
      if (depth > max1) {
        max2 = max1;
        max1 = depth;
      } else if (depth > max2) {
        max2 = depth;
      }
    }
    diameter = Math.max(diameter, max1 + max2);
    return max1 + 1;
  }

  dfs(0, -1);
  return diameter;
}

const tree = {
  0: [1, 2],
  1: [0, 3, 4]
};

console.log(treeDiameter(tree));
ATypeError because tree[node] can be undefined
BSyntaxError due to missing semicolon
CRuntime error due to infinite recursion
DNo error, outputs correct diameter
Attempts:
2 left
💡 Hint
Check if all nodes have entries in the tree object.
🚀 Application
advanced
1:30remaining
Calculate diameter for a star-shaped tree
Given a star-shaped tree with 1 center node connected to 5 leaf nodes, what is the diameter of this tree?
A6
B5
C1
D2
Attempts:
2 left
💡 Hint
The diameter is the longest path between two leaves through the center.
❓ Predict Output
expert
2:30remaining
Output of diameter calculation on a complex tree
What is the output of this TypeScript code that calculates the diameter of a more complex tree?
DSA Typescript
type Tree = { [key: number]: number[] };

function treeDiameter(tree: Tree): number {
  let diameter = 0;

  function dfs(node: number, parent: number): number {
    let max1 = 0, max2 = 0;
    for (const child of tree[node] || []) {
      if (child === parent) continue;
      const depth = dfs(child, node);
      if (depth > max1) {
        max2 = max1;
        max1 = depth;
      } else if (depth > max2) {
        max2 = depth;
      }
    }
    diameter = Math.max(diameter, max1 + max2);
    return max1 + 1;
  }

  dfs(0, -1);
  return diameter;
}

const tree = {
  0: [1, 2],
  1: [0, 3, 4],
  2: [0, 5],
  3: [1, 6],
  4: [1],
  5: [2, 7, 8],
  6: [3],
  7: [5],
  8: [5]
};

console.log(treeDiameter(tree));
A6
B7
C5
D8
Attempts:
2 left
💡 Hint
Find the longest path between any two nodes in the tree.

Practice

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

Solution

  1. Step 1: Understand the definition of diameter

    The diameter is the longest path between any two nodes in a tree, not just from the root.
  2. Step 2: Differentiate from other tree properties

    Height is the longest path from root to leaf, number of nodes and leaves are counts, not paths.
  3. Final Answer:

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

    Diameter = Longest path [OK]
Hint: Diameter is longest path between any two nodes [OK]
Common Mistakes:
  • Confusing diameter with height
  • Thinking diameter counts nodes instead of path length
  • Assuming diameter is from root only
2. Which TypeScript data structure is best to represent a tree for diameter calculation?
easy
A. Boolean flag
B. String array
C. Number variable
D. Array of edges (adjacency list)

Solution

  1. Step 1: Identify tree representation needs

    We need to store connections between nodes, so adjacency list (array of edges) is suitable.
  2. Step 2: Eliminate unsuitable types

    String array, number variable, or boolean flag cannot represent node connections effectively.
  3. Final Answer:

    Array of edges (adjacency list) -> Option D
  4. Quick Check:

    Adjacency list = Array of edges [OK]
Hint: Use adjacency list (array of edges) for tree representation [OK]
Common Mistakes:
  • Using simple variables instead of lists
  • Confusing data types with tree structure
  • Using string arrays for numeric node connections
3. What is the output of the following TypeScript code that calculates the diameter of a tree?
const tree = {
  0: [1, 2],
  1: [0, 3],
  2: [0],
  3: [1]
};

function dfs(node: number, parent: number): number {
  let max1 = 0, max2 = 0;
  for (const child of tree[node]) {
    if (child === parent) continue;
    const dist = dfs(child, node) + 1;
    if (dist > max1) {
      max2 = max1;
      max1 = dist;
    } else if (dist > max2) {
      max2 = dist;
    }
  }
  diameter = Math.max(diameter, max1 + max2);
  return max1;
}

let diameter = 0;
dfs(0, -1);
console.log(diameter);
medium
A. 2
B. 3
C. 4
D. 1

Solution

  1. Step 1: Trace DFS from node 0

    From node 0, children are 1 and 2. DFS(1) returns 2 (path 1->3), DFS(2) returns 1. dist from 1: 3, from 2: 2.
  2. Step 2: Calculate diameter updates

    At node 0, max1=2, max2=1, diameter updated to 3 (2+1). No larger path found elsewhere.
  3. Final Answer:

    3 -> Option B
  4. Quick Check:

    Longest path length = 3 [OK]
Hint: Sum two longest child paths at each node for diameter [OK]
Common Mistakes:
  • Ignoring parent to avoid cycles
  • Not updating diameter with sum of two longest paths
  • Returning wrong distance from DFS
4. Find the bug in this TypeScript code snippet that tries to compute the diameter of a tree:
const tree = {
  0: [1],
  1: [0, 2],
  2: [1]
};

let diameter = 0;
function dfs(node: number): number {
  let max1 = 0, max2 = 0;
  for (const child of tree[node]) {
    const dist = dfs(child) + 1;
    if (dist > max1) {
      max2 = max1;
      max1 = dist;
    } else if (dist > max2) {
      max2 = dist;
    }
  }
  diameter = Math.max(diameter, max1 + max2);
  return max1;
}
dfs(0);
console.log(diameter);
medium
A. Missing parent parameter to avoid revisiting nodes
B. Diameter variable is not initialized
C. DFS function should return diameter instead of max1
D. Tree is not defined as an array

Solution

  1. Step 1: Identify infinite recursion cause

    DFS revisits parent node because no parent check, causing infinite recursion.
  2. Step 2: Fix by adding parent parameter

    Pass parent node to DFS and skip it in children loop to avoid cycles.
  3. Final Answer:

    Missing parent parameter to avoid revisiting nodes -> Option A
  4. Quick Check:

    Parent check prevents infinite recursion [OK]
Hint: Pass parent node in DFS to avoid cycles [OK]
Common Mistakes:
  • Not skipping parent node in DFS
  • Confusing diameter initialization
  • Returning wrong values from DFS
5. Given a weighted tree represented as an adjacency list with edges and weights, how would you modify the diameter calculation to find the longest weighted path?
const tree = {
  0: [{node:1, weight:3}, {node:2, weight:2}],
  1: [{node:0, weight:3}, {node:3, weight:4}],
  2: [{node:0, weight:2}],
  3: [{node:1, weight:4}]
};
hard
A. Ignore weights and count edges only
B. Use BFS instead of DFS without weight consideration
C. Add edge weights to distances during DFS and update diameter accordingly
D. Calculate diameter by counting number of nodes only

Solution

  1. Step 1: Incorporate weights in DFS distance calculation

    Instead of adding 1 for each edge, add the edge's weight to the distance.
  2. Step 2: Update diameter with sum of two longest weighted paths

    Keep track of two longest weighted distances from children and update diameter with their sum.
  3. Final Answer:

    Add edge weights to distances during DFS and update diameter accordingly -> Option C
  4. Quick Check:

    Weighted distances sum = diameter [OK]
Hint: Sum edge weights in DFS for weighted diameter [OK]
Common Mistakes:
  • Ignoring weights and counting edges only
  • Using BFS without weights
  • Counting nodes instead of path weights
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