Print all leaf nodes of a Binary Tree from left to right | Java program to print leaf nodes from left to right ; A Binary Tree Node ; Function to print leaf nodes from left to right ; If node is null , return ; If node is leaf node , print its data ; If left child exists , check for leaf recursively ; If right child exists , check for leaf recursively ; Utility function to create a new tree node ; Driver code ; Let us create binary tree shown in above diagram ; Print leaf nodes of the given tree
import java . util . * ; class GFG { static class Node { public int data ; public Node left , right ; } ; static void printLeafNodes ( Node root ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { System . out . print ( root . data + " ▁ " ) ; return ; } if ( root . left != null ) printLeafNodes ( root . left ) ; if ( root . right != null ) printLeafNodes ( root . right ) ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = null ; temp . right = null ; return temp ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . right . left = newNode ( 5 ) ; root . right . right = newNode ( 8 ) ; root . right . left . left = newNode ( 6 ) ; root . right . left . right = newNode ( 7 ) ; root . right . right . left = newNode ( 9 ) ; root . right . right . right = newNode ( 10 ) ; printLeafNodes ( root ) ; } }