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.

Try It Yourself
redirect icon

[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.
C++
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

vector<int> extremeNodes(Node* root) {
    
    vector<int> res;
    
    if (root == nullptr) return res;
    
    queue<Node*> q;
    q.push(root);
    
    bool rightExtreme = true;
    
    while (!q.empty()) {
        
        int size = q.size();
        
        Node* left = q.front(), *right = q.front();
        
        // Traverse the nodes of current level.
        while (size--) {
            
            Node* curr = q.front();
            q.pop();
            
            // If left subtree exists 
            if (curr->left != nullptr) {
                q.push(curr->left);
            }
            
            // If right subtree exists 
            if (curr->right != nullptr) {
                q.push(curr->right);
            }
            
            // Set right node 
            right = curr;
        }
        
        // Append left or right node 
        if (rightExtreme) {
            res.push_back(right->data);
        }
        else {
            res.push_back(left->data);
        }
        
        // Flip the value
        rightExtreme = !rightExtreme;
    }
    
    return res;
}

int main() {
    
    // Hard coded binary tree
    //           1
    //         /   \
    //       2      3
    //     /  \
    //   4     5
    //  /
    // 7
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->left->left->left = new Node(7);

    vector<int> res = extremeNodes(root);
    for (auto val: res) cout << val << " ";
    cout << endl;
    return 0;
}
Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

class Node {
    int data;
    Node left, right;
    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    static ArrayList<Integer> extremeNodes(Node root) {
        ArrayList<Integer> res = new ArrayList<>();
        
        if (root == null) return res;
        
        Queue<Node> q = new LinkedList<>();
        q.add(root);
        
        boolean rightExtreme = true;
        
        while (!q.isEmpty()) {
            int size = q.size();
            
            Node left = q.peek(), right = q.peek();
            
            // Traverse the nodes of current level.
            while (size-- > 0) {
                Node curr = q.poll();
                
                // If left subtree exists 
                if (curr.left != null) {
                    q.add(curr.left);
                }
                
                // If right subtree exists 
                if (curr.right != null) {
                    q.add(curr.right);
                }
                
                // Set right node 
                right = curr;
            }
            
            // Append left or right node 
            if (rightExtreme) {
                res.add(right.data);
            }
            else {
                res.add(left.data);
            }
            
            // Flip the value
            rightExtreme = !rightExtreme;
        }
        
        return res;
    }

    public static void main(String[] args) {
        
        // Hard coded binary tree
        //           1
        //         /   \
        //       2      3
        //     /  \
        //   4     5
        //  /
        // 7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.left.left.left = new Node(7);

        ArrayList<Integer> res = extremeNodes(root);
        for (int val : res) System.out.print(val + " ");
        System.out.println();
    }
}
Python
from collections import deque

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

def extremeNodes(root):
    res = []
    
    if root is None:
        return res
    
    q = deque()
    q.append(root)
    
    rightExtreme = True
    
    while q:
        size = len(q)
        
        left = q[0]
        right = q[0]
        
        # Traverse the nodes of current level.
        while size > 0:
            curr = q.popleft()
            size -= 1
            
            # If left subtree exists 
            if curr.left is not None:
                q.append(curr.left)
            
            # If right subtree exists 
            if curr.right is not None:
                q.append(curr.right)
            
            # Set right node 
            right = curr
        
        # Append left or right node 
        if rightExtreme:
            res.append(right.data)
        else:
            res.append(left.data)
        
        # Flip the value
        rightExtreme = not rightExtreme
    
    return res

if __name__ == "__main__":
    
    # Hard coded binary tree
    #           1
    #         /   \
    #       2      3
    #     /  \
    #   4     5
    #  /
    # 7
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.left.left.left = Node(7)

    res = extremeNodes(root)
    for val in res:
        print(val, end=" ")
    print()
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;
    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    static List<int> extremeNodes(Node root) {
        List<int> res = new List<int>();
        
        if (root == null) return res;
        
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
        
        bool rightExtreme = true;
        
        while (q.Count > 0) {
            int size = q.Count;
            
            Node left = q.Peek(), right = q.Peek();
            
            // Traverse the nodes of current level.
            while (size-- > 0) {
                Node curr = q.Dequeue();
                
                // If left subtree exists 
                if (curr.left != null) {
                    q.Enqueue(curr.left);
                }
                
                // If right subtree exists 
                if (curr.right != null) {
                    q.Enqueue(curr.right);
                }
                
                // Set right node 
                right = curr;
            }
            
            // Append left or right node 
            if (rightExtreme) {
                res.Add(right.data);
            }
            else {
                res.Add(left.data);
            }
            
            // Flip the value
            rightExtreme = !rightExtreme;
        }
        
        return res;
    }

    static void Main() {
        
        // Hard coded binary tree
        //           1
        //         /   \
        //       2      3
        //     /  \
        //   4     5
        //  /
        // 7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.left.left.left = new Node(7);

        List<int> res = extremeNodes(root);
        foreach (int val in res) Console.Write(val + " ");
        Console.WriteLine();
    }
}
JavaScript
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

function extremeNodes(root) {
    let res = [];
    
    if (root === null) return res;
    
    let q = [];
    q.push(root);
    
    let rightExtreme = true;
    
    while (q.length > 0) {
        let size = q.length;
        
        let left = q[0], right = q[0];
        
        // Traverse the nodes of current level.
        while (size-- > 0) {
            let curr = q.shift();
            
            // If left subtree exists 
            if (curr.left !== null) {
                q.push(curr.left);
            }
            
            // If right subtree exists 
            if (curr.right !== null) {
                q.push(curr.right);
            }
            
            // Set right node 
            right = curr;
        }
        
        // Append left or right node 
        if (rightExtreme) {
            res.push(right.data);
        }
        else {
            res.push(left.data);
        }
        
        // Flip the value
        rightExtreme = !rightExtreme;
    }
    
    return res;
}
// Hard coded binary tree
//           1
//         /   \
//       2      3
//     /  \
//   4     5
//  /
// 7
// driver code
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.left.left.left = new Node(7);

let res = extremeNodes(root);
console.log(res.join(" "));

Output
1 2 5 7 
Comment