how to print leaf nodes of a binary tree in java

This is 7th part of java binary tree tutorial.

In this post, we will see about program to print leaf nodes in a binary tree in java

Algorithm-

Steps for counting number of leaf nodes are:
  • If node is null then return 0
  • If encounterd leaf node(i.e. node.left is null and node.right is null) then print the node.
  • Recursively visit leaf subtree and right subtree.

Code for recursion will be:

Example:
Binary tree:

Lets create java program for counting number of leaf nodes:

Run above program and you will get following output:

Java Binary tree tutorial:

Add Comment