Skip to content

Tree Views & Traversals: Zig-Zag, Boundary, Top, Bottom, Left & Right View Problems

📚 Overview of this Lecture

This video covers 7 important binary tree problems frequently asked in technical interviews:

  1. Zig-Zag (Spiral) Traversal
  2. Boundary Traversal
  3. Vertical Order Traversal
  4. Top View
  5. Bottom View
  6. Left View
  7. Right View (Homework: Diagonal Traversal)

For more systematic problem-solving strategies, check out 8 Essential LeetCode Patterns to Solve Coding Problems Efficiently.

🔄 1. Zig-Zag Traversal (Spiral Traversal)

Concept: Print nodes level by level, alternating between left-to-right and right-to-left direction.

Approach (Level Order + Direction Flag):

  • Use a queue for level order traversal
  • Maintain a boolean flag leftToRight to track direction
  • For each level:
    • Create a temporary array to store nodes of that level
    • If leftToRight is true → insert nodes normally (index = i)
    • If leftToRight is false → insert nodes in reverse order (index = size - i - 1)
  • Toggle the flag after processing each level

Time Complexity: O(n) | Space Complexity: O(n)

🚧 2. Boundary Traversal

Concept: Print tree boundary in anti-clockwise direction: left boundary → leaf nodes → right boundary (reverse).

3-Step Approach:

Part 1: Print Left Boundary (excluding leaf nodes)

void traverseLeft(Node* root, vector<int> &ans) {
    // Base case
    if(root == NULL || (root->left == NULL && root->right == NULL))
        return;
    
    // Store current node
    ans.push_back(root->data);
    
    // Go left if exists, else go right
    if(root->left)
        traverseLeft(root->left, ans);
    else
        traverseLeft(root->right, ans);
}

Part 2: Print Leaf Nodes (inorder traversal)

Simply traverse left to right and collect all leaf nodes.

Part 3: Print Right Boundary (excluding leaf nodes, in reverse order)

Traverse right boundary and store nodes, but push them into answer array after the recursive call completes (to get reverse order).

📐 3. Vertical Order Traversal

Concept: Print nodes based on their horizontal distance from root, from left to right.

Key Data Structures:

// Map: horizontal_distance -> level -> nodes vector
map<int, map<int, vector<int>>> nodes;

// Queue: node + (horizontal distance, level)
queue<pair<Node*, pair<int, int>>> q;

How to assign Horizontal Distance (HD):

  • Root: HD = 0
  • Going left: HD = currentHD - 1
  • Going right: HD = currentHD + 1

Algorithm:

  1. Use level order traversal
  2. For each node, store it in nodes[HD][level]
  3. After traversal, extract nodes in order of HD (sorted by map keys), then by level

👁️ 4. Top View of Binary Tree

Concept: Nodes visible when viewing tree from the top (first node at each horizontal distance).

Approach (Level Order + Map):

topNode[hd] = frontNode->data;  // Only first time per HD
  • Use level order traversal
  • Create a map: hd -> nodeData
  • Key condition: Only insert if no node already exists for that HD (the first node at that HD blocks all others)

🔻 5. Bottom View of Binary Tree

Concept: Nodes visible when viewing tree from the bottom (last node at each horizontal distance).

Approach (Simpler than Top View):

  • Use same level order traversal
  • No condition check , simply overwrite the map entry with each node
  • The last node encountered at each HD remains in the map

Key Difference from Top View: | Top View | Bottom View | |----------|------------| | Check if HD exists before inserting | Always overwrite | | First node at HD wins | Last node at HD wins |

👈 6. Left View of Binary Tree

Concept: Nodes visible when viewing from the left side (first node at each level from left).

Recursive Approach:

void solve(Node* root, vector<int> &ans, int level) {
    // Base case
    if(root == NULL) return;
    
    // We entered a new level
    if(level == ans.size())
        ans.push_back(root->data);
    
    // First go left, then right
    solve(root->left, ans, level+1);
    solve(root->right, ans, level+1);
}

Time Complexity: O(n) | Space Complexity: O(height)

👉 7. Right View of Binary Tree

Concept: Same as left view, but process right subtree first.

Simple Modification from Left View:

  • Swap the recursive calls:
solve(root->right, ans, level+1);  // Process right first
solve(root->left, ans, level+1);   // Then left

📝 Homework: Diagonal Traversal

Hint:

  • When going right → horizontal distance (HD) remains the same
  • When going left → decrease HD by 1
  • Map nodes by their HD and print in order

💡 Key Takeaways

  1. Views are about HD mapping , Top (first), Bottom (last), Left (first at level), Right (first at level from right)
  2. Level order traversal is your friend for most view problems
  3. Recursion works beautifully for left/right view problems
  4. Practice the pattern , most tree view problems follow similar logic with minor modifications. For a deeper understanding of the data structures used, see Comprehensive Guide to Core Data Structures and Algorithms.

⏰ Time & Space Complexity Summary

| Problem | Time | Space | |---------|------|-------| | Zig-Zag Traversal | O(n) | O(n) | | Boundary Traversal | O(n) | O(n) | | Vertical Order | O(n log n) | O(n) | | Top View | O(n log n) | O(n) | | Bottom View | O(n log n) | O(n) | | Left/Right View | O(n) | O(height) |

Keep this summary

Save it to LunaNotes and it becomes a real note in your library — editable, searchable, and ready to turn into flashcards or a diagram. Free to start.

Save to LunaNotes

Or summarise for another video.

32K+ people have turned 65K+ videos into notes

“Very useful tool. I'm using it for the last couple weeks and I'm loving it so far. Makes learning on YouTube a great experience.”
Bhai Chrome Web Store review

This summary and transcript were automatically generated using AI with the Free YouTube transcript summary tool by LunaNotes.

Related summaries

8 Essential LeetCode Patterns to Solve Coding Problems Efficiently

8 Essential LeetCode Patterns to Solve Coding Problems Efficiently

After solving over 500 LeetCode problems, the key insight is to focus on repeating patterns rather than individual solutions. This video outlines 8 fundamental patterns—including sliding window, subset, modified binary search, and two-pointer—that can simplify complex coding challenges and improve problem-solving speed.

Binary Tree Introduction: Types, Terms & Fundamentals

Binary Tree Introduction: Types, Terms & Fundamentals

Learn the basics of binary trees including key terminology like root, children, leaf nodes, and ancestors. This video also covers the five main types of binary trees: full, complete, perfect, balanced, and degenerate, with clear examples for each.

Comprehensive Guide to Core Data Structures and Algorithms

Comprehensive Guide to Core Data Structures and Algorithms

Explore foundational concepts in data structures, computational complexity, and advanced algorithms. This guide covers arrays, linked lists, stacks, queues, priority queues, union-find, trees, hash tables, Fenwick trees, suffix arrays, balanced BSTs, and indexed priority queues, with insights on implementation and performance optimization.

Comprehensive Guide to Data Structures: Arrays to Graphs Explained

Comprehensive Guide to Data Structures: Arrays to Graphs Explained

Explore fundamental concepts of data structures from arrays, lists, stacks, queues to trees and graphs. Learn definitions, real-world examples, implementation strategies, and algorithmic insights for efficient data organization and manipulation.

Bit Manipulation in Java: Get, Set, Clear & Update Bit Operations

Bit Manipulation in Java: Get, Set, Clear & Update Bit Operations

Learn bit manipulation in Java with this comprehensive guide covering 4 major bit operations: Get, Set, Clear, and Update. Understand bitmasking techniques, left/right shift operators, and see practical code examples to master placement and programming interview questions.

Found this summary useful?

Take it with you. One click puts it in your own LunaNotes library.

Save to LunaNotes

Start taking better notes today with LunaNotes