0
0
DSA Javascriptprogramming

Tree Terminology Root Leaf Height Depth Level in DSA Javascript

Choose your learning style9 modes available
Mental Model
A tree is like a family tree where each person is connected to parents and children. We use special names for the top person, the bottom people, and how far each person is from the top.
Analogy: Imagine a family tree: the oldest ancestor is the root, the youngest children with no kids are leaves, height is how tall the family tree is, depth is how far a person is from the oldest ancestor, and level is the generation number.
        Root (A)
       /       \
    (B)         (C)
   /   \          \
 (D)   (E)        (F)

Legend:
- Root: A
- Leaves: D, E, F
- Height: longest path from root to leaf
- Depth: distance from root to a node
- Level: depth + 1
Dry Run Walkthrough
Input: Tree with nodes: A(root), B and C children of A, D and E children of B, F child of C
Goal: Understand root, leaf, height, depth, and level for each node
Step 1: Identify the root node
Root: A
Tree: A -> B, C -> D, E, F
Why: Root is the top node with no parent
Step 2: Identify leaf nodes
Leaves: D, E, F
Tree: A -> B, C -> D, E, F
Why: Leaves have no children
Step 3: Calculate height of tree
Height = 3 (A to D or A to F path length)
Why: Height is longest path from root to any leaf
Step 4: Calculate depth of node E
Depth(E) = 2 (A -> B -> E)
Why: Depth is number of edges from root to node
Step 5: Calculate level of node E
Level(E) = 3 (depth + 1)
Why: Level counts nodes from root as 1
Result:
Root: A
Leaves: D, E, F
Height: 3
Depth(E): 2
Level(E): 3
Annotated Code
DSA Javascript
class TreeNode {
  constructor(value) {
    this.value = value;
    this.children = [];
  }
}

// Function to find height of tree
function treeHeight(node) {
  if (!node) return 0;
  if (node.children.length === 0) return 1; // leaf node
  let heights = node.children.map(child => treeHeight(child));
  return 1 + Math.max(...heights);
}

// Function to find depth of a node given root
function findDepth(root, target, depth = 0) {
  if (!root) return -1;
  if (root.value === target) return depth;
  for (let child of root.children) {
    let d = findDepth(child, target, depth + 1);
    if (d !== -1) return d;
  }
  return -1;
}

// Function to find leaves
function findLeaves(node, leaves = []) {
  if (!node) return leaves;
  if (node.children.length === 0) leaves.push(node.value);
  for (let child of node.children) {
    findLeaves(child, leaves);
  }
  return leaves;
}

// Driver code
const A = new TreeNode('A');
const B = new TreeNode('B');
const C = new TreeNode('C');
const D = new TreeNode('D');
const E = new TreeNode('E');
const F = new TreeNode('F');

A.children.push(B, C);
B.children.push(D, E);
C.children.push(F);

console.log('Root:', A.value);
console.log('Leaves:', findLeaves(A).join(', '));
console.log('Height:', treeHeight(A));
const target = 'E';
const depthE = findDepth(A, target);
console.log(`Depth(${target}):`, depthE);
console.log(`Level(${target}):`, depthE + 1);
if (node.children.length === 0) return 1; // leaf node
return 1 for leaf node height base case
let heights = node.children.map(child => treeHeight(child));
recursively get heights of all children
return 1 + Math.max(...heights);
height is 1 plus max height among children
if (root.value === target) return depth;
found target node, return current depth
let d = findDepth(child, target, depth + 1);
search children increasing depth by 1
if (node.children.length === 0) leaves.push(node.value);
collect leaf nodes with no children
OutputSuccess
Root: A Leaves: D, E, F Height: 3 Depth(E): 2 Level(E): 3
Complexity Analysis
Time: O(n) because we visit each node once to calculate height, depth, or leaves
Space: O(h) where h is tree height due to recursion stack
vs Alternative: Iterative approaches may use queues but still visit all nodes, so similar O(n) time
Edge Cases
Empty tree (root is null)
Height is 0, no leaves, depth queries return -1
DSA Javascript
if (!node) return 0;
Single node tree
Root is also leaf, height is 1, depth of root is 0
DSA Javascript
if (node.children.length === 0) return 1;
Target node not found for depth
Returns -1 indicating node not present
DSA Javascript
return -1;
When to Use This Pattern
When a problem involves hierarchical data or family-like relationships, recognize tree terminology to navigate and measure nodes effectively.
Common Mistakes
Mistake: Confusing depth and level by forgetting level is depth plus one
Fix: Remember level counts nodes starting at 1 for root, so level = depth + 1
Mistake: Assuming leaf nodes have children or missing them
Fix: Check children length equals zero to identify leaves
Summary
Defines key tree terms: root (top node), leaf (no children), height (longest path from root), depth (distance from root), and level (depth plus one).
Use when working with tree structures to understand node positions and tree shape.
The aha moment is seeing the tree like a family tree with generations and distances from the oldest ancestor.