Print leftmost and rightmost nodes of a Binary Tree | Java program to print corner node at each level in a binary tree ; A binary tree node has key , pointer to left child and a pointer to right child ; Function to print corner node at each level ; star node is for keeping track of levels ; pushing root node and star node ; Do level order traversal of Binary Tree ; n is the no of nodes in current Level ; If it is leftmost corner value or rightmost corner value then print it ; push the left and right children of the temp node ; Driver program to test above functions
import java . util . * ; class Node { int key ; Node left , right ; public Node ( int key ) { this . key = key ; left = right = null ; } } class BinaryTree { Node root ; void printCorner ( Node root ) { Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; while ( ! q . isEmpty ( ) ) { int n = q . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Node temp = q . peek ( ) ; q . poll ( ) ; if ( i == 0 i == n - 1 ) System . out . print ( temp . key + " ▁ " ) ; if ( temp . left != null ) q . add ( temp . left ) ; if ( temp . right != null ) q . add ( temp . right ) ; } } } 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 ) ; } }