/* Binary Tree Structure: 20 / \ 8 22 / \ \ 5 3 25 / \ 10 14 */ // Bottom view prints nodes visible when the tree is viewed from the bottom. // Expected output format: node values from left to right as a list. // Assume horizontal distance (hd) from root: root=0, left=-1, right=+1, etc. // Bottom view nodes: 5, 10, 3, 14, 25 // Output: [5, 10, 3, 14, 25]
The bottom view shows the last node at each horizontal distance when viewed from bottom.
At hd=-2: 5
At hd=-1: 10 (overwrites 8 because 10 is lower)
At hd=0: 3 (overwrites 20)
At hd=1: 14
At hd=2: 25
Horizontal distance (hd) measures how far left or right a node is from the root node.
Root has hd=0, left child hd=parent hd - 1, right child hd=parent hd + 1.
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* left; struct Node* right; }; void bottomView(struct Node* root) { if (!root) return; int hd = 0; // Missing data structure to store nodes by hd bottomView(root->left); printf("%d ", root->data); bottomView(root->right); } int main() { struct Node* root = malloc(sizeof(struct Node)); root->data = 1; root->left = NULL; root->right = NULL; bottomView(root); return 0; }
The code performs an inorder traversal and prints nodes but does not track horizontal distances or levels.
Bottom view requires tracking nodes by horizontal distance and choosing the lowest node at each distance.
Horizontal distances and bottom nodes:
- hd=-2: 4
- hd=-1: 2
- hd=0: 6 (overwrites 1 and 5)
- hd=1: 8
- hd=2: 7
- hd=3: 9
The queue supports level order traversal to visit nodes breadth-first.
The map stores the most recent node at each horizontal distance, ensuring the bottom-most node is recorded.
