Bird
Raised Fist0
DSA Typescriptprogramming

Bottom View of Binary Tree in DSA Typescript

Choose your learning style10 modes available
Mental Model
We want to see the nodes visible if we look at the tree from the bottom. Each vertical line shows the lowest node at that horizontal position.
Analogy: Imagine standing under a tree and looking up. You only see the lowest leaves or branches directly above you, not the ones hidden behind or higher up.
       20
      /  \
    8     22
   / \      \
  5   3      25
     / \     
    10  14

Horizontal distances:
- 20 at 0
- 8 at -1
- 22 at 1
- 5 at -2
- 3 at 0
- 25 at 2
- 10 at -1
- 14 at 1
Dry Run Walkthrough
Input: Binary tree: 20 / \ 8 22 / \ \ 5 3 25 / \ 10 14 Find bottom view
Goal: Find nodes visible from bottom: one node per horizontal distance, the lowest one in the tree
Step 1: Start BFS from root (20) at horizontal distance 0
Queue: [(20, hd=0)]
Bottom view map: {}
Why: We begin from root to explore all nodes level by level with their horizontal distances
Step 2: Pop (20,0), update bottom view at hd=0 with 20
Queue: []
Bottom view map: {0: 20}
Why: First node at hd=0 is 20, so bottom view at 0 is 20
Step 3: Add left child (8, hd=-1) and right child (22, hd=1) to queue
Queue: [(8,-1), (22,1)]
Bottom view map: {0: 20}
Why: Children are added with updated horizontal distances
Step 4: Pop (8,-1), update bottom view at hd=-1 with 8
Queue: [(22,1)]
Bottom view map: {0: 20, -1: 8}
Why: First node at hd=-1 is 8
Step 5: Add left child (5,-2) and right child (3,0) of 8 to queue
Queue: [(22,1), (5,-2), (3,0)]
Bottom view map: {0: 20, -1: 8}
Why: Add children with their horizontal distances
Step 6: Pop (22,1), update bottom view at hd=1 with 22
Queue: [(5,-2), (3,0)]
Bottom view map: {0: 20, -1: 8, 1: 22}
Why: First node at hd=1 is 22
Step 7: Add right child (25,2) of 22 to queue
Queue: [(5,-2), (3,0), (25,2)]
Bottom view map: {0: 20, -1: 8, 1: 22}
Why: Add child with hd=2
Step 8: Pop (5,-2), update bottom view at hd=-2 with 5
Queue: [(3,0), (25,2)]
Bottom view map: {0: 20, -1: 8, 1: 22, -2: 5}
Why: First node at hd=-2 is 5
Step 9: Pop (3,0), update bottom view at hd=0 with 3 (overwrite 20)
Queue: [(25,2)]
Bottom view map: {0: 3, -1: 8, 1: 22, -2: 5}
Why: 3 is lower than 20 at hd=0, so update bottom view
Step 10: Add left child (10,-1) and right child (14,1) of 3 to queue
Queue: [(25,2), (10,-1), (14,1)]
Bottom view map: {0: 3, -1: 8, 1: 22, -2: 5}
Why: Add children with their horizontal distances
Step 11: Pop (25,2), update bottom view at hd=2 with 25
Queue: [(10,-1), (14,1)]
Bottom view map: {0: 3, -1: 8, 1: 22, -2: 5, 2: 25}
Why: First node at hd=2 is 25
Step 12: Pop (10,-1), update bottom view at hd=-1 with 10 (overwrite 8)
Queue: [(14,1)]
Bottom view map: {0: 3, -1: 10, 1: 22, -2: 5, 2: 25}
Why: 10 is lower than 8 at hd=-1, update bottom view
Step 13: Pop (14,1), update bottom view at hd=1 with 14 (overwrite 22)
Queue: []
Bottom view map: {0: 3, -1: 10, 1: 14, -2: 5, 2: 25}
Why: 14 is lower than 22 at hd=1, update bottom view
Result:
-2: 5 -> -1: 10 -> 0: 3 -> 1: 14 -> 2: 25
Bottom view nodes: 5 10 3 14 25
Annotated Code
DSA Typescript
class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val: number) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

function bottomView(root: TreeNode | null): number[] {
  if (!root) return [];

  // Map to store the bottom view nodes: hd -> node.val
  const hdNodeMap = new Map<number, number>();

  // Queue for BFS: stores pairs of node and its horizontal distance
  const queue: Array<{node: TreeNode; hd: number}> = [];
  queue.push({node: root, hd: 0});

  while (queue.length > 0) {
    const {node, hd} = queue.shift()!;

    // Update bottom view for this horizontal distance
    hdNodeMap.set(hd, node.val);

    // Add left child with hd-1
    if (node.left) {
      queue.push({node: node.left, hd: hd - 1});
    }

    // Add right child with hd+1
    if (node.right) {
      queue.push({node: node.right, hd: hd + 1});
    }
  }

  // Extract bottom view nodes sorted by horizontal distance
  const sortedKeys = Array.from(hdNodeMap.keys()).sort((a, b) => a - b);
  return sortedKeys.map(key => hdNodeMap.get(key)!);
}

// Driver code to build tree and print bottom view
const root = new TreeNode(20);
root.left = new TreeNode(8);
root.right = new TreeNode(22);
root.left.left = new TreeNode(5);
root.left.right = new TreeNode(3);
root.right.right = new TreeNode(25);
root.left.right.left = new TreeNode(10);
root.left.right.right = new TreeNode(14);

const result = bottomView(root);
console.log(result.join(' '));
queue.push({node: root, hd: 0});
Initialize BFS queue with root at horizontal distance 0
const {node, hd} = queue.shift()!;
Dequeue next node and its horizontal distance for processing
hdNodeMap.set(hd, node.val);
Update bottom view map with current node at this horizontal distance
if (node.left) { queue.push({node: node.left, hd: hd - 1}); }
Add left child with horizontal distance one less
if (node.right) { queue.push({node: node.right, hd: hd + 1}); }
Add right child with horizontal distance one more
const sortedKeys = Array.from(hdNodeMap.keys()).sort((a, b) => a - b);
Sort horizontal distances to output bottom view left to right
return sortedKeys.map(key => hdNodeMap.get(key)!);
Return bottom view nodes in order of horizontal distance
OutputSuccess
5 10 3 14 25
Complexity Analysis
Time: O(n) because we visit each node once during BFS
Space: O(n) for the queue and map storing nodes and horizontal distances
vs Alternative: Compared to recursive vertical order traversal, BFS with map is simpler and efficient for bottom view
Edge Cases
Empty tree (root is null)
Returns empty array as there are no nodes
DSA Typescript
if (!root) return [];
Tree with single node
Returns array with only that node's value
DSA Typescript
queue.push({node: root, hd: 0});
Tree with all nodes on one side (left or right)
Bottom view is all nodes in a line with increasing or decreasing horizontal distances
DSA Typescript
hdNodeMap.set(hd, node.val);
When to Use This Pattern
When asked to find nodes visible from bottom or side in a tree, use BFS with horizontal distances to track and update visible nodes.
Common Mistakes
Mistake: Not updating the bottom view map when a lower node at the same horizontal distance is found
Fix: Always overwrite the map entry for a horizontal distance during BFS to keep the lowest node
Mistake: Using DFS which may not process nodes level by level, causing incorrect bottom view
Fix: Use BFS to process nodes level by level ensuring bottom nodes overwrite top ones
Summary
Finds the nodes visible when looking at a binary tree from the bottom.
Use when you need to see the lowest nodes at each horizontal position in a tree.
The key is to track horizontal distances and overwrite nodes at each distance during a level order traversal.

Practice

(1/5)
1. What does the bottom view of a binary tree represent?
easy
A. Nodes visible when the tree is viewed from the left side
B. Nodes visible when the tree is viewed from the top
C. Nodes visible when the tree is viewed from the bottom
D. Nodes visible when the tree is viewed from the right side

Solution

  1. Step 1: Understand the bottom view concept

    The bottom view of a binary tree includes nodes that are visible when looking at the tree from below, meaning the lowest nodes at each horizontal distance.
  2. Step 2: Compare with other views

    Top view shows nodes visible from above, left view from left side, right view from right side. Bottom view is distinct as it shows the lowest nodes at each horizontal position.
  3. Final Answer:

    Nodes visible when the tree is viewed from the bottom -> Option C
  4. Quick Check:

    Bottom view = visible nodes from below [OK]
Hint: Bottom view shows lowest nodes at each horizontal distance [OK]
Common Mistakes:
  • Confusing bottom view with top view
  • Thinking bottom view shows all leaf nodes
  • Mixing bottom view with left or right side views
2. Which TypeScript data structure is best suited to store nodes by their horizontal distance when computing the bottom view?
easy
A. Array
B. Map (key-value pairs)
C. Set
D. Stack

Solution

  1. Step 1: Identify the need to map horizontal distances

    We need to associate each horizontal distance with the node visible at that distance in the bottom view.
  2. Step 2: Choose a data structure for key-value mapping

    A Map allows storing keys (horizontal distances) with corresponding node values, enabling easy updates and retrieval.
  3. Final Answer:

    Map (key-value pairs) -> Option B
  4. Quick Check:

    Use Map for horizontal distance to node mapping [OK]
Hint: Use Map to link horizontal distance with nodes [OK]
Common Mistakes:
  • Using Array which is index-based, not key-based
  • Using Set which stores unique values but no keys
  • Using Stack which is LIFO, not suitable for mapping
3. What is the output bottom view of the binary tree represented by the following code?
class Node {
  constructor(public data: number, public left: Node | null = null, public right: Node | null = null) {}
}

const root = new Node(20,
  new Node(8,
    new Node(5),
    new Node(3, null, new Node(10))
  ),
  new Node(22, null, new Node(25))
);
medium
A. [5, 8, 3, 10, 25]
B. [5, 10, 3, 22, 25]
C. [8, 3, 10, 22, 25]
D. [5, 3, 10, 22, 25]

Solution

  1. Step 1: Assign horizontal distances and track nodes

    Horizontal distances: 20(0), 8(-1), 22(1), 5(-2), 3(0), 10(1), 25(2). Level order traversal order: 20(0), 8(-1), 22(1), 5(-2), 3(0), 25(2), 10(1). For bottom view, the last node encountered at each hd.
  2. Step 2: Determine bottom view nodes by horizontal distance

    hd -2:5; -1:8; 0:3 (overwrites 20); 1:10 (overwrites 22); 2:25. Sorted left-to-right: [5, 8, 3, 10, 25].
  3. Final Answer:

    [5, 8, 3, 10, 25] -> Option A
  4. Quick Check:

    Bottom view nodes = [5, 8, 3, 10, 25] [OK]
Hint: Track last node at each horizontal distance [OK]
Common Mistakes:
  • Choosing first node at horizontal distance instead of last
  • Mixing horizontal distances incorrectly
  • Ignoring right child nodes at same horizontal distance
4. Identify the bug in this TypeScript code snippet for bottom view of a binary tree:
function bottomView(root: Node | null): number[] {
  if (!root) return [];
  const map = new Map();
  const queue: Array<{node: Node; hd: number}> = [{node: root, hd: 0}];
  while (queue.length) {
    const {node, hd} = queue.shift()!;
    if (!map.has(hd)) {
      map.set(hd, node.data);
    }
    if (node.left) queue.push({node: node.left, hd: hd - 1});
    if (node.right) queue.push({node: node.right, hd: hd + 1});
  }
  return Array.from(map.values());
}
medium
A. It only stores the first node at each horizontal distance, not the bottom-most
B. It uses shift() which is inefficient for queue
C. It does not check if root is null
D. It returns keys instead of values from the map

Solution

  1. Step 1: Analyze map update condition

    The code sets map value only if horizontal distance is not present, so it keeps the first node at that distance.
  2. Step 2: Understand bottom view requirement

    Bottom view requires the last (bottom-most) node at each horizontal distance, so map should update value every time a node at that hd is found.
  3. Final Answer:

    It only stores the first node at each horizontal distance, not the bottom-most -> Option A
  4. Quick Check:

    Bottom view needs last node per hd, code stores first [OK]
Hint: Update map value for every node at horizontal distance [OK]
Common Mistakes:
  • Not updating map for later nodes at same horizontal distance
  • Confusing top view logic with bottom view
  • Ignoring null root check (though present here)
5. Given a binary tree where multiple nodes share the same horizontal distance and depth, how should the bottom view algorithm decide which node to display?
hard
A. Display the node with the smallest value at that horizontal distance
B. Display the node with the largest depth but smallest horizontal distance
C. Display the node that appears first in level order traversal at that horizontal distance
D. Display the node that appears last in level order traversal at that horizontal distance

Solution

  1. Step 1: Understand node selection criteria for bottom view

    Bottom view shows the lowest node at each horizontal distance. When multiple nodes share horizontal distance and depth, the one encountered last in level order traversal is visible.
  2. Step 2: Clarify why last in level order matters

    Level order visits nodes top to bottom, left to right. The last node at a horizontal distance overwrites previous ones, ensuring bottom-most visibility.
  3. Final Answer:

    Display the node that appears last in level order traversal at that horizontal distance -> Option D
  4. Quick Check:

    Bottom view = last node per hd in level order [OK]
Hint: Choose last node at horizontal distance in level order [OK]
Common Mistakes:
  • Choosing node by value instead of position
  • Selecting first node instead of last at horizontal distance
  • Confusing horizontal distance with depth
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