VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-extreme-nodes-of-each-level-of-binary-tree-in-alternate-order/

⇱ Print extreme nodes of each level of Binary Tree in alternate order - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print extreme nodes of each level of Binary Tree in alternate order

Last Updated : 27 Feb, 2026

Given a Binary Tree, print the nodes at the extreme corners (leftmost or rightmost) of each level in alternate order.

Example:

Input: Binary Tree

👁 420851466

Output: 1 2 5 7
Explanation: The tree is traversed level by level.

  • Level 0 - Select right extreme - 1
  • Level 1 - Select left extreme - 2
  • Level 2 - Select right extreme - 5
  • Level 3 - Select left extreme - 7

At each level, we alternately choose the rightmost and leftmost node.

[Approach] Iterative Approach - O(n) Time and O(n) Space

The idea is to traverse the binary tree using level order traversal. For each level, print the left extreme node or right extreme node based on the level.

Step by step approach:

  • Create a queue and insert the root node into it.
  • Initialize a boolean variable rightExtreme and set it to true to indicate that the right extreme node is required first.
  • For each level, determine the number of nodes currently present in the queue.
  • Traverse all nodes of that level one by one.
  • During traversal, treat the first node as the extreme left and the last node as the extreme right.
  • If rightExtreme is true, append the right extreme node; otherwise, append the left extreme node.
  • Toggle the value of rightExtreme after processing each level.

Output
1 2 5 7 
Comment
Article Tags:
Article Tags: