how to print leaf nodes of a binary tree in java

Last updated on June 4th, 2017 at 12:25 am

Previous
Next

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:

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog