Get level of a node in binary tree in java

If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.

This is 11th part of java binary tree tutorial.

Java Binary tree tutorial:

In this post, we will see about program to get level of node  in a binary tree in java.
We will search for a key in binary tree. Root will be at level 1. If we do not find key in binary tree then its level will be 0.

Algorithm :

Steps for getting level of a node in binary tree:
  • If node is null then return 0
  • If node’s data is equal to key, then return level.
  • Recursively search key in left subtree
  • If not found, then search in right subtree

Code for recursion will be:

Lets create java program to get level of node in binary tree:

Lets say, your binary tree is this:

Run above program and you will get following output:

Java Binary tree tutorial:

Please go through Interview programs in java  for more such programs.

import_contacts

You may also like:

Related Posts

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.