Given a binary tree, we need to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree.
Example :
All leaf nodes of above binary tree is :
4 5 3
To print all leaf nodes traverse the tree in Preorder fashion, processing the root first, then the right sub-tree, then the left sub-tree, and do the following:
- Checks if the specified node is null. If it is null, it returns from the function.
- Check if it is a leaf node. If the node is a leaf node, it prints its data.
- If in the previous step the node is not a leaf node, check if the left and right child node exists. If so, recursively call the function for the left and right children of the node.
Example – Program to Print all leaves of a binary tree in Java
public class LeafNodes { public static void main(String[] args) throws Exception { Tree bt = new Tree("1"); root = bt; root.left = new Tree("2"); root.left.left = new Tree("4"); root.left.right = new Tree("5"); root.right = new Tree("3"); printLeaves(root); } private static class Tree { String value; Tree left; Tree right; Tree(String value) { this.value = value; } boolean isLeaf() { return left == null ? right == null : false; } } static Tree root; public static void printLeaves(Tree node) { if (node == null) { return; } if (node.isLeaf()) { System.out.printf("%s ", node.value); } printLeaves(node.left); printLeaves(node.right); } }
Output
4 5 3
Example – Another way
public class LeafNodes { static class Tree { int data; Tree left, right; }; static Tree newNode(int data) { Tree temp = new Tree(); temp.data = data; temp.left = temp.right = null; return temp; } static void printLeafNodes(Tree root) { if (root == null) return; if (root.left == null && root.right == null) { System.out.print(root.data + " "); return; } // If left child exists, check for leaf if (root.left != null) printLeafNodes(root.left); // If right child exists, check for leaf if (root.right != null) printLeafNodes(root.right); } public static void main(String args[]) { Tree root = newNode(1); root.left = newNode(2); root.left.left = newNode(4); root.left.right = newNode(5); root.right = newNode(3); printLeafNodes(root); } }
Output
4 5 3