Bird
Raised Fist0
DSA Typescriptprogramming~10 mins

DP on Trees Diameter of Tree in DSA Typescript - Execution Trace

Choose your learning style10 modes available
Concept Flow - DP on Trees Diameter of Tree
Start at any node
↓
Run DFS to find farthest node A
↓
Run DFS from node A to find farthest node B
↓
Diameter is distance between A and B
↓
Use DP to store max depths during DFS
↓
Update diameter with max sum of two depths at each node
↓
Return final diameter
Find diameter by two DFS traversals and use DP to store max depths for efficient calculation.
Execution Sample
DSA Typescript
function diameterOfTree(adj: number[][]): number {
  let diameter = 0;
  function dfs(node: number, parent: number): number {
    let max1 = 0, max2 = 0;
    for (const child of adj[node]) {
      if (child === parent) continue;
      const depth = dfs(child, node) + 1;
      if (depth > max1) {
        max2 = max1;
        max1 = depth;
      } else if (depth > max2) {
        max2 = depth;
      }
    }
    diameter = Math.max(diameter, max1 + max2);
    return max1;
  }
  dfs(0, -1);
  return diameter;
}
Calculate tree diameter by DFS and DP storing max depths at each node.
Execution Table
StepOperationNode VisitedMax Depths (max1, max2)Diameter UpdateVisual State
1Start DFS from node 00(0,0)diameter=00
2Visit child 1 of node 01(0,0)diameter=00 -> 1
3Visit child 3 of node 13(0,0)diameter=00 -> 1 -> 3
4Return depth 1 from node 33(0,0)diameter=00 -> 1 -> 3
5Update max depths at node 1: max1=1, max2=01(1,0)diameter=00 -> 1
6Visit child 2 of node 02(0,0)diameter=00 -> 2
7Visit child 4 of node 24(0,0)diameter=00 -> 2 -> 4
8Return depth 1 from node 44(0,0)diameter=00 -> 2 -> 4
9Update max depths at node 2: max1=1, max2=02(1,0)diameter=00 -> 2
10Update max depths at node 0: max1=1 (from 1), max2=1 (from 2)0(1,1)diameter=20
11Diameter updated to max1+max2=20(1,1)diameter=2Tree diameter path length = 2
12DFS complete, return diameter--diameter=2Final diameter = 2
💡 DFS completes after visiting all nodes; diameter is max sum of two max depths at any node.
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 9After Step 10Final
diameter000022
max1 (node 0)000011
max2 (node 0)000011
max1 (node 1)011111
max2 (node 1)000000
max1 (node 2)000111
max2 (node 2)000000
Key Moments - 3 Insights
Why do we keep track of two max depths (max1 and max2) at each node?
Because the diameter can pass through the current node combining two longest paths from its children. See execution_table step 10 where diameter updates using max1 + max2.
Why do we ignore the parent node during DFS?
To avoid revisiting the node we came from and prevent infinite loops. This is shown in the code snippet where child === parent is skipped.
How does the diameter relate to the max depths stored at nodes?
Diameter is the longest path between any two nodes, which equals the sum of two largest depths from a node. Execution_table step 11 shows diameter updated as max1 + max2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 10, what are the max depths (max1, max2) at node 0?
A(0,0)
B(2,0)
C(1,1)
D(1,0)
💡 Hint
Check the 'Max Depths (max1, max2)' column at step 10 in execution_table.
At which step does the diameter first update to a non-zero value?
AStep 5
BStep 10
CStep 9
DStep 12
💡 Hint
Look at the 'Diameter Update' column in execution_table to find when diameter changes from 0.
If the tree had only one node, what would be the diameter according to variable_tracker?
A0
B1
CUndefined
D2
💡 Hint
Diameter starts at 0 and only updates when there are edges; see 'diameter' variable in variable_tracker.
Concept Snapshot
DP on Trees Diameter:
- Use DFS twice or DP during DFS
- Track two max depths (max1, max2) at each node
- Diameter = max sum of max1 + max2 over all nodes
- Ignore parent in DFS to avoid cycles
- Return final diameter after DFS completes
Full Transcript
To find the diameter of a tree, we run a depth-first search (DFS) starting from any node to find the farthest node A. Then, we run DFS again from node A to find the farthest node B. The distance between A and B is the diameter. During DFS, we use dynamic programming to store the two largest depths (max1 and max2) from each node's children. The diameter is updated as the maximum sum of these two depths at any node. We skip the parent node during DFS to avoid revisiting nodes. The final diameter is returned after all nodes are visited.

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