Binary Tree View Implementations
A comprehensive guide to binary tree traversal and view algorithms for Data Structures and Algorithms.
Table of Contents
- Basic Node Structures
- Tree Construction Helpers
- Top View Implementation
- Bottom View Implementation
- Left View Implementation
- Right View Implementation
- Boundary Traversal
- Vertical Order Traversal
- Level Order Views
- Diagonal Views
- Advanced View Techniques
- Usage Examples
Basic Node Structures
The foundation of binary tree operations starts with node definitions:
Binary Tree Node
class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
Enhanced Node with Coordinates
class TreeNodeWithCoords {
constructor(val = 0, left = null, right = null, row = 0, col = 0) {
this.val = val;
this.left = left;
this.right = right;
this.row = row; // Level/depth
this.col = col; // Horizontal distance
}
}
Tree Construction Helpers
Create Tree from Array (Level Order)
function createTreeFromArray(arr) {
if (!arr || arr.length === 0) return null;
const root = new TreeNode(arr[0]);
const queue = [root];
let i = 1;
while (queue.length > 0 && i < arr.length) {
const node = queue.shift();
if (i < arr.length && arr[i] !== null) {
node.left = new TreeNode(arr[i]);
queue.push(node.left);
}
i++;
if (i < arr.length && arr[i] !== null) {
node.right = new TreeNode(arr[i]);
queue.push(node.right);
}
i++;
}
return root;
}
Print Tree Structure
function printTree(root, prefix = "", isLast = true) {
if (!root) return;
console.log(prefix + (isLast ? "└── " : "├── ") + root.val);
const children = [root.left, root.right].filter(Boolean);
children.forEach((child, index) => {
const isLastChild = index === children.length - 1;
const newPrefix = prefix + (isLast ? " " : "│ ");
printTree(child, newPrefix, isLastChild);
});
}
Top View Implementation
1. Top View (Horizontal Distance Based)
Concept: View the tree from above - only the topmost node at each horizontal distance is visible.
function topView(root) {
if (!root) return [];
const map = new Map();
const queue = [[root, 0]]; // [node, horizontal_distance]
while (queue.length > 0) {
const [node, hd] = queue.shift();
// Only add if this horizontal distance hasn't been seen
if (!map.has(hd)) {
map.set(hd, node.val);
}
if (node.left) queue.push([node.left, hd - 1]);
if (node.right) queue.push([node.right, hd + 1]);
}
// Sort by horizontal distance and return values
return Array.from(map.entries())
.sort((a, b) => a[0] - b[0])
.map(([_, val]) => val);
}
Time Complexity: O(n log n) | Space Complexity: O(n)