The Wayback Machine - https://web.archive.org/web/20240809094129/https://www.geeksforgeeks.org/print-leftmost-and-rightmost-nodes-of-a-binary-tree/
Open In App

Print leftmost and rightmost nodes of a Binary Tree

Last Updated : 11 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a Binary Tree, Print the corner nodes at each level. The node at the leftmost and the node at the rightmost. 
For example, the output for the following is 15, 10, 20, 8, 25. 

A Simple Solution is to do two traversals using the approaches discussed for printing left view and right view. 

Can we print all corner nodes using one traversal? 
The idea is to use Level Order Traversal. Every time we store the size of the queue in a variable n, which is the number of nodes at that level. For every level, we check whether the current node is the first (i.e node at index 0) and the node at the last index (i.e node at index n-1) If it is either of them, we print the value of that node.  

Implementation:

C++




// C/C++ program to print corner node at each level
// of binary tree
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has key, pointer to left
   child and a pointer to right child */
struct Node
{
    int key;
    struct Node* left, *right;
};
 
/* To create a newNode of tree and return pointer */
struct Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
 
/* Function to print corner node at each level */
void printCorner(Node *root)
{
    //If the root is null then simply return
    if(root == NULL)
        return;
    //Do level order traversal using a single queue
    queue<Node*> q;
    q.push(root);
    
    while(!q.empty())
    {
        //n denotes the size of the current level in the queue
        int n = q.size();
         
        for(int i =0;i<n;i++)
        {
            Node *temp = q.front();
            q.pop();
             
            //If it is leftmost corner value or rightmost corner value then print it
            if(i==0 || i==n-1)
               cout<<temp->key<<" ";
 
            //push the left and right children of the temp node
            if(temp->left)
                q.push(temp->left);
            if(temp->right)
                q.push(temp->right);
        }
    }
}
// Driver program to test above function
int main ()
{
    Node *root =  newNode(15);
    root->left = newNode(10);
    root->right = newNode(20);
    root->left->left = newNode(8);
    root->left->right = newNode(12);
    root->right->left = newNode(16);
    root->right->right = newNode(25);
    printCorner(root);
    return 0;
}
 
// This code is contributed by Tapeshdua420.


Java




// Java program to print corner node at each level in a binary tree
 
import java.util.*;
 
/* A binary tree node has key, pointer to left
   child and a pointer to right child */
class Node
{
    int key;
    Node left, right;
 
    public Node(int key)
    {
        this.key = key;
        left = right = null;
    }
}
 
class BinaryTree
{
    Node root;
 
    /* Function to print corner node at each level */
    void printCorner(Node root)
    {
        //  star node is for keeping track of levels
        Queue<Node> q = new LinkedList<Node>();
 
        // pushing root node and star node
        q.add(root);
        // Do level order traversal of Binary Tree
        while (!q.isEmpty())
        {
            // n is the no of nodes in current Level
            int n = q.size();
            for(int i = 0 ; i < n ; i++){
            // dequeue the front node from the queue
            Node temp = q.peek();
            q.poll();
            //If it is leftmost corner value or rightmost corner value then print it
            if(i==0 || i==n-1)
                System.out.print(temp.key + "  ");
            //push the left and right children of the temp node
            if (temp.left != null)
                q.add(temp.left);
            if (temp.right != null)
                q.add(temp.right);
        }
        }
 
    }
 
    // Driver program to test above functions
    public static void main(String[] args)
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(15);
        tree.root.left = new Node(10);
        tree.root.right = new Node(20);
        tree.root.left.left = new Node(8);
        tree.root.left.right = new Node(12);
        tree.root.right.left = new Node(16);
        tree.root.right.right = new Node(25);
 
        tree.printCorner(tree.root);
    }
}
 
// This code has been contributed by Utkarsh Choubey


Python3




# Python3 program to print corner
# node at each level of binary tree
from collections import deque
 
# A binary tree node has key, pointer to left
# child and a pointer to right child
class Node:
    def __init__(self, key):
         
        self.key = key
        self.left = None
        self.right = None
 
# Function to print corner node at each level
def printCorner(root: Node):
 
    # If the root is null then simply return
    if root == None:
        return
 
    # Do level order traversal
    # using a single queue
    q = deque()
    q.append(root)
 
    while q:
 
        # n denotes the size of the current
        # level in the queue
        n = len(q)
        for i in range(n):
            temp = q[0]
            q.popleft()
 
            # If it is leftmost corner value or
            # rightmost corner value then print it
            if i == 0 or i == n - 1:
                print(temp.key, end = " ")
 
            # push the left and right children
            # of the temp node
            if temp.left:
                q.append(temp.left)
            if temp.right:
                q.append(temp.right)
 
# Driver Code
if __name__ == "__main__":
     
    root = Node(15)
    root.left = Node(10)
    root.right = Node(20)
    root.left.left = Node(8)
    root.left.right = Node(12)
    root.right.left = Node(16)
    root.right.right = Node(25)
     
    printCorner(root)
 
# This code is contributed by sanjeev2552


C#




// C# program to print corner node
// at each level in a binary tree
using System;
using System.Collections.Generic;
 
/* A binary tree node has key, pointer to left
child and a pointer to right child */
public class Node
{
    public int key;
    public Node left, right;
 
    public Node(int key)
    {
        this.key = key;
        left = right = null;
    }
}
 
public class BinaryTree
{
    Node root;
 
    /* Function to print corner node at each level */
    void printCorner(Node root)
    {
        // star node is for keeping track of levels
        Queue<Node> q = new Queue<Node>();
 
        // pushing root node and star node
        q.Enqueue(root);
        // Do level order traversal of Binary Tree
        while (q.Count != 0)
        {
            // n is the no of nodes in current Level
            int n = q.Count;
            for(int i = 0 ; i < n ; i++){
                Node temp = q.Peek();
                q.Dequeue();
                //If it is leftmost corner value or rightmost corner value then print it
                if(i==0||i==n-1)
                    Console.Write(temp.key + " ");
            //push the left and right children of the temp node
                if (temp.left != null)
                    q.Enqueue(temp.left);
                if (temp.right != null)
                    q.Enqueue(temp.right);
 
            }
        }
 
}
 
    // Driver code
    public static void Main(String[] args)
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(15);
        tree.root.left = new Node(10);
        tree.root.right = new Node(20);
        tree.root.left.left = new Node(8);
        tree.root.left.right = new Node(12);
        tree.root.right.left = new Node(16);
        tree.root.right.right = new Node(25);
 
        tree.printCorner(tree.root);
    }
}
 
// This code is contributed by Utkarsh Choubey


Javascript




// JavaScript Program to print corner node at each level
// of binary tree
 
// A binary tree node has key, pointer to left
// child and a pointer to right child
class Node{
    constructor(val){
        this.key = val;
        this.left = null;
        this.right = null;
    }
}
 
// Function to print corner node at each level
function printCorner(root){
    // if the root is null then simply return
    if(root == null) return;
     
    // Do level order traversal using a single queue
    var q = [];
    q.push(root);
    while(q.length != 0){
        // n denotes the size of the current level in the queue
        var n = q.length;
         
        for(let i = 0; i < n; i++){
            let temp = q.shift();
             
            // If it is leftmost or rightmost corner value than print it
            if(i == 0 || i == n-1){
               console.log(temp.key);
            }
             
            // push the left and right children of the temp node
            if(temp.left != null) q.push(temp.left);
            if(temp.right != null) q.push(temp.right);
        }
    }
}
 
// Driver program to test above function
var root = new Node(15);
root.left = new Node(10);
root.right = new Node(20);
root.left.left = new Node(8);
root.left.right = new Node(12);
root.right.left = new Node(16);
root.right.right = new Node(25);
 
printCorner(root);
 
// This code is contributed by Yash Agarwal(yashagarwal2852002)


Output

15 10 20 8 25 

Time Complexity: O(n) where n is the number of nodes in the Binary Tree.
Auxiliary Space: O(n).



Similar Reads

Leftmost and rightmost indices of the maximum and the minimum element of an array
Given an array arr[], the task is to find the leftmost and the rightmost indices of the minimum and the maximum element from the array where arr[] consists of non-distinct elements.Examples: Input: arr[] = {2, 1, 1, 2, 1, 5, 6, 5} Output: Minimum left : 1 Minimum right : 4 Maximum left : 6 Maximum right : 6 Minimum element is 1 which is present at
15+ min read
Print all the nodes except the leftmost node in every level of the given binary tree
Given a binary tree, the task is to print all the nodes except the leftmost in every level of the tree. The root is considered at level 0, and left most node of any level is considered as a node at position 0. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 3 5 6 8 10 Input: 1 / \ 2 3 \ \ 4 5 Output: 3 5 Approach: To print nodes lev
8 min read
Find Leftmost and Rightmost node of BST from its given preorder traversal
Given a preorder sequence of the binary search tree of N nodes. The task is to find its leftmost and rightmost nodes. Examples: Input : N = 5, preorder[]={ 3, 2, 1, 5, 4 } Output : Leftmost = 1, Rightmost = 5 The BST constructed from this preorder sequence would be: 3 / \ 2 5 / / 1 4 Leftmost Node of this tree is equal to 1 Rightmost Node of this t
5 min read
Print all nodes except rightmost node of every level of the Binary Tree
Given a binary tree, the task is to print all the nodes except the rightmost in every level of the tree. The root is considered at level 0, and rightmost node of any level is considered as a node at position 0.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 2 4 5 7 9 Input: 1 / \ 2 3 \ \ 4 5 Output: 2 4 Approach: To print nodes leve
7 min read
Find array elements with rightmost set bit at the position of the rightmost set bit in K
Given an array arr[] consisting of N and an integer K, the task is to print the elements of arr[] whose rightmost set bit is at the same position as the rightmost set bit in K. Examples: Input: arr[] = { 3, 4, 6, 7, 9, 12, 15 }, K = 7Output: { 3, 7, 9, 15 }Explanation:Binary representation of K (= 7) is 0111.Rightmost set bit in 7 is at position 1.
11 min read
Leftmost Column with atleast one 1 in a row-wise sorted binary matrix
Given a binary matrix mat[][] containing 0's and 1's. Each row of the matrix is sorted in the non-decreasing order, the task is to find the left-most column of the matrix with at least one 1 in it.Note: If no such column exists return -1.Examples: Input: mat[2][2] = { {0, 0}, {1, 1} } Output: 1 Explanation: The 1st column of the matrix contains atl
8 min read
Leftmost Column with atleast one 1 in a row-wise sorted binary matrix | Set 2
Given a binary matrix mat[][] containing 0’s and 1’s. Each row of the matrix is sorted in the non-decreasing order, the task is to find the left-most column of the matrix with at least one 1 in it.Note: If no such column exists return -1. Examples: Input: mat[][] = {{0, 0, 0, 1} {0, 1, 1, 1} {0, 0, 1, 1}} Output: 2 Explanation: The 2nd column of th
5 min read
Position of leftmost set bit in given binary string where all 1s appear at end
Given a binary string S of length N, such that all 1s appear on the right. The task is to return the index of the first set bit found from the left side else return -1. Examples: Input: s = 00011, N = 5Output: 3Explanation: The first set bit from the left side is at index 3. Input: s = 0000, N = 4Output: -1 Approach: This problem can be solved usin
5 min read
Repeated Character Whose First Appearance is Leftmost
Given a string, find the repeated character present first in the string. Examples: Input: geeksforgeeksOutput: g Input: abcdabcdOutput: a Input: abcdOutput: -1 Brute Force Approach: The brute force approach to solve this problem is to consider each character in the string and then check whether it appears again in the remaining part of the string.
14 min read
Minimize replacements of leftmost largest array element required to make all array elements equal
Given an array arr[] consisting of N integers, the task is to make all array elements equal by replacing the leftmost largest element of the array with the largest element strictly smaller than the current maximum minimum number of times. Examples: Input: arr[] = { 1, 1, 2, 2, 3&lt;}Output: 4Explanation: Following operations reduces the required nu
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg