Bird
Raised Fist0
DSA Typescriptprogramming~20 mins

Graph vs Tree Key Structural Difference in DSA Typescript - Compare & Choose

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Graph vs Tree Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Key Structural Difference Between Graph and Tree
Which of the following statements correctly describes the key structural difference between a graph and a tree?
AA tree is a connected graph with no cycles, while a graph can have cycles and may be disconnected.
BA graph always has a root node, but a tree does not have a root.
CA tree can have cycles, but a graph cannot have cycles.
DA graph is always directed, while a tree is always undirected.
Attempts:
2 left
💡 Hint
Think about connectivity and cycles in both structures.
❓ Predict Output
intermediate
1:30remaining
Output of Graph vs Tree Edge Count
Given a tree with 5 nodes, what is the number of edges it must have?
DSA Typescript
const nodes = 5;
const edgesInTree = nodes - 1;
console.log(edgesInTree);
A6
B4
C5
D3
Attempts:
2 left
💡 Hint
Remember the formula for edges in a tree.
❓ Predict Output
advanced
2:30remaining
Detecting Cycle in Graph Code Output
What is the output of the following TypeScript code that checks for a cycle in an undirected graph?
DSA Typescript
class Graph {
  adjacencyList: Map<number, number[]> = new Map();

  addEdge(u: number, v: number) {
    if (!this.adjacencyList.has(u)) this.adjacencyList.set(u, []);
    if (!this.adjacencyList.has(v)) this.adjacencyList.set(v, []);
    this.adjacencyList.get(u)!.push(v);
    this.adjacencyList.get(v)!.push(u);
  }

  hasCycle(): boolean {
    const visited = new Set<number>();

    const dfs = (node: number, parent: number): boolean => {
      visited.add(node);
      for (const neighbor of this.adjacencyList.get(node) || []) {
        if (!visited.has(neighbor)) {
          if (dfs(neighbor, node)) return true;
        } else if (neighbor !== parent) {
          return true;
        }
      }
      return false;
    };

    for (const node of this.adjacencyList.keys()) {
      if (!visited.has(node)) {
        if (dfs(node, -1)) return true;
      }
    }
    return false;
  }
}

const g = new Graph();
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(4, 1);
console.log(g.hasCycle());
ASyntaxError
Bfalse
Cundefined
Dtrue
Attempts:
2 left
💡 Hint
Check if the edges form a cycle.
🧠 Conceptual
advanced
2:00remaining
Why Trees Cannot Have Cycles
Why is it impossible for a tree to have a cycle?
ABecause trees are defined as connected graphs with exactly one path between any two nodes.
BBecause trees have multiple paths between nodes.
CBecause trees allow cycles only if they are directed.
DBecause trees always have disconnected nodes.
Attempts:
2 left
💡 Hint
Think about the uniqueness of paths in a tree.
❓ Predict Output
expert
2:30remaining
Output of Graph Connectivity Check
What is the output of this TypeScript code that checks if an undirected graph is connected?
DSA Typescript
class Graph {
  adjacencyList: Map<number, number[]> = new Map();

  addEdge(u: number, v: number) {
    if (!this.adjacencyList.has(u)) this.adjacencyList.set(u, []);
    if (!this.adjacencyList.has(v)) this.adjacencyList.set(v, []);
    this.adjacencyList.get(u)!.push(v);
    this.adjacencyList.get(v)!.push(u);
  }

  isConnected(): boolean {
    const visited = new Set<number>();
    const nodes = Array.from(this.adjacencyList.keys());
    if (nodes.length === 0) return true;

    const dfs = (node: number) => {
      visited.add(node);
      for (const neighbor of this.adjacencyList.get(node) || []) {
        if (!visited.has(neighbor)) dfs(neighbor);
      }
    };

    dfs(nodes[0]);
    return visited.size === nodes.length;
  }
}

const g = new Graph();
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(4, 5);
console.log(g.isConnected());
ATypeError
Btrue
Cfalse
Dundefined
Attempts:
2 left
💡 Hint
Check if all nodes are reachable from the first node.

Practice

(1/5)
1. Which of the following is a key structural difference between a tree and a graph?
easy
A. A graph is always directed, but a tree is always undirected.
B. A graph always has a root node, but a tree does not.
C. A tree can have multiple edges between the same nodes, but a graph cannot.
D. A tree has no cycles, but a graph can have cycles.

Solution

  1. Step 1: Understand the cycle property in trees and graphs

    A tree is a special type of graph that does not contain any cycles, meaning no path loops back to the same node.
  2. Step 2: Compare cycle allowance in graphs

    Graphs can have cycles, meaning they can contain loops where you can start at a node and return to it by following edges.
  3. Final Answer:

    A tree has no cycles, but a graph can have cycles. -> Option D
  4. Quick Check:

    Tree no cycles, graph can have cycles = D [OK]
Hint: Trees never loop back; graphs can have loops [OK]
Common Mistakes:
  • Thinking graphs must have a root node
  • Believing trees can have cycles
  • Confusing edge multiplicity rules
2. Which of the following TypeScript declarations correctly represents a tree node structure?
easy
A. interface Node { value: number; neighbors: Node[]; }
B. interface Node { value: number; parent: Node[]; }
C. interface Node { value: number; children: Node[]; }
D. interface Node { value: number; edges: number[]; }

Solution

  1. Step 1: Identify tree node properties

    A tree node typically has a value and a list of children nodes, representing a hierarchical structure.
  2. Step 2: Match the correct interface

    interface Node { value: number; children: Node[]; } uses children: Node[], which correctly models tree children. Other options use neighbors or parent arrays, which are more graph-like or incorrect.
  3. Final Answer:

    interface Node { value: number; children: Node[]; } -> Option C
  4. Quick Check:

    Tree nodes have children array = B [OK]
Hint: Trees use children arrays, graphs use neighbors [OK]
Common Mistakes:
  • Using neighbors instead of children for trees
  • Confusing parent arrays with children
  • Using edges as numbers instead of nodes
3. Consider this TypeScript code snippet representing a graph and a tree. What will be the output of the console.log statements?
medium
A. "Graph has cycles: true, Tree has cycles: false"
B. "Graph has cycles: false, Tree has cycles: true"
C. "Graph has cycles: false, Tree has cycles: false"
D. "Graph has cycles: true, Tree has cycles: true"

Solution

  1. Step 1: Analyze the graph structure for cycles

    The graph has edges forming a cycle (e.g., node1 -> node2 -> node3 -> node1), so it contains cycles.
  2. Step 2: Analyze the tree structure for cycles

    The tree is built with parent-child links and no back edges, so it has no cycles.
  3. Final Answer:

    "Graph has cycles: true, Tree has cycles: false" -> Option A
  4. Quick Check:

    Graph cycles true, tree cycles false = A [OK]
Hint: Graphs can cycle, trees cannot [OK]
Common Mistakes:
  • Assuming trees can have cycles
  • Ignoring cycle detection in graphs
  • Confusing output strings
4. The following TypeScript code attempts to build a tree but has a structural error. What is the main issue?
medium
A. The tree nodes have multiple parents, violating tree structure.
B. The tree nodes use neighbors instead of children arrays.
C. The tree nodes have cycles due to incorrect parent references.
D. The tree root node is missing a value property.

Solution

  1. Step 1: Check parent references in the tree nodes

    Each tree node should have only one parent. Multiple parents mean the structure is not a tree.
  2. Step 2: Identify multiple parents in the code

    The code assigns two different parents to a single node, creating multiple parent links and breaking the tree property.
  3. Final Answer:

    The tree nodes have multiple parents, violating tree structure. -> Option A
  4. Quick Check:

    Multiple parents break tree rules = C [OK]
Hint: Trees have one parent per node only [OK]
Common Mistakes:
  • Confusing neighbors with children
  • Ignoring multiple parent assignments
  • Missing value property is not main error
5. You need to convert a graph into a tree by removing edges. Which key structural property must you ensure after removal?
hard
A. The resulting structure must have at least one cycle.
B. The resulting structure must be connected and have no cycles.
C. The resulting structure must have multiple parents for some nodes.
D. The resulting structure must allow multiple edges between same nodes.

Solution

  1. Step 1: Understand tree properties

    A tree is a connected structure with no cycles and exactly one path between any two nodes.
  2. Step 2: Apply properties to graph conversion

    To convert a graph to a tree, remove edges to eliminate cycles but keep the graph connected.
  3. Final Answer:

    The resulting structure must be connected and have no cycles. -> Option B
  4. Quick Check:

    Tree = connected + no cycles = A [OK]
Hint: Tree = connected graph without cycles [OK]
Common Mistakes:
  • Allowing cycles in the tree
  • Permitting multiple parents
  • Keeping multiple edges between nodes
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