If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
This is 11th part of java binary tree tutorial.

Java Binary tree tutorial:

    Binary tree in java Binary tree preorder traversal Binary tree postorder traversal Binary tree inorder traversal Binary tree level order traversal Binary tree spiral order traversal Print leaf nodes of binary tree Count leaf nodes in binary tree Print all paths from root to leaf in binary tree Print vertical sum of binary tree in java

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:

/* To get level of node in a binary tree*/
  public static int getLevelOfNode(TreeNode root,int key,int level)
 {
  if(root==null)
   return 0;
  if(root.data==key)
   return level;
  
  int result=getLevelOfNode(root.left,key,level+1) ;
  if(result!=0)
  { 
   // If found in left subtree , return 
   return result;
  
  }
  result= getLevelOfNode(root.right,key,level+1);
 
  return result;
 }

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

Lets say, your binary tree is this:
package org.arpit.java2blog;

public class BinaryTree {

 
 public static class TreeNode
 {
  int data;
  TreeNode left;
  TreeNode right;
  TreeNode(int data)
  {
   this.data=data;
  }
 }
 
 // Recursive Solution
//To get level of node in a binary tree
 public static int getLevelOfNode(TreeNode root,int key,int level)
 {
  if(root==null)
   return 0;
  if(root.data==key)
   return level;
  
  int result=getLevelOfNode(root.left,key,level+1) ;
  if(result!=0)
  { 
   // If found in left subtree , return 
   return result;
  }
  result= getLevelOfNode(root.right,key,level+1);
 
  return result;
 }

 
 public static void main(String[] args)
 {
  BinaryTree bi=new BinaryTree();
  // Creating a binary tree
  TreeNode rootNode=createBinaryTree();
  System.out.println("Node data: 70,Level :"+getLevelOfNode(rootNode, 70, 1));
  System.out.println("Node data: 100,Level :"+getLevelOfNode(rootNode, 100, 1));
  System.out.println("Node data: 60,Level :"+getLevelOfNode(rootNode, 60, 1));
  System.out.println("Node data: 40,Level :"+getLevelOfNode(rootNode, 40, 1));
 }
 
 public static TreeNode createBinaryTree()
 {
  
  TreeNode rootNode =new TreeNode(40);
  TreeNode node20=new TreeNode(20);
  TreeNode node10=new TreeNode(10);
  TreeNode node30=new TreeNode(30);
  TreeNode node60=new TreeNode(60);
  TreeNode node50=new TreeNode(50);
  TreeNode node70=new TreeNode(70);
  
  rootNode.left=node20;
  rootNode.right=node60;
  
  node20.left=node10;
  node20.right=node30;
  
  node60.left=node50;
  node60.right=node70;
  
  return rootNode;
 }
}

Run above program and you will get following output:
 
Node data: 70,Level :3
Node data: 100,Level :0
Node data: 60,Level :2
Node data: 40,Level :1

Java Binary tree tutorial:

    Binary tree in java Binary tree preorder traversal Binary tree postorder traversal Binary tree inorder traversal Binary tree level order traversal Binary tree spiral order traversal Binary tree reverse level order traversal Binary tree boundary traversal Print leaf nodes of binary tree Count leaf nodes in binary tree get maximum element in binary tree Print all paths from root to leaf in binary tree Print vertical sum of binary tree in java Get level of node in binary tree in java Lowest common ancestor(LCA) in binary tree in java
Please go through Interview programs in java  for more such programs.

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

Java Linked List Interview Programs:

    How to reverse a linked list in java How to reverse a linked list in pairs in java How to find middle element of linked list in java How to detect a loop in linked list in java Find start node of loop in linkedlist How to find nth element from end of linked list How to check if linked list is palindrome in java Add two numbers represented by linked list in java
Given two number represent by linked list, calculate sum of the numbers and store result in new linked list. Each node of linked list is represented by single digit and head node is most significant digit.
For example:
Sum of two number:
   56712
+   6359
-----------
   63071

So it will be represented in below format as linked list:

Algorithm:

  • Create two linkedlist which will represent above two numbers.
  • Reverse both linked list.
  • Add two node values (Each node is being represented as single digit)  starting from heads of two linkedlist.
  • If sum is of above two node values is more than 10, then forward the carry.
  • Follow basic mathematical rules for addition.
Below image will make it clear:

  • Reverse the result , so that we will get actual sum of numbers.

Java program:

 
package org.arpit.java2blog;


public class AddTwoNumberLinkedList{
 /*
  * @Author: Arpit Mandliya
  * */
 private static Node head;

 private static class Node {
  private int value;
  private Node next;

  Node(int value) {
   this.value = value;

  }
 }

 public void addToTheLast(Node node) {

  if (head == null) {
   head = node;
  } else {
   Node temp = head;
   while (temp.next != null)
    temp = temp.next;

   temp.next = node;
  }
 }


 public void printList(Node printNode) {
  Node temp = printNode;
  while (temp != null) {
   System.out.format("%d ", temp.value);
   temp = temp.next;
  }
  System.out.println();
 }

 public static Node reverseLinkedList(Node node) {
      if (node == null || node.next == null) {
          return node;
      }

      Node remaining = reverseLinkedList(node.next);
      node.next.next = node;
      node.next = null;
     return remaining;
  }

 // This function will do sum of numbers represented by linked list
 public Node findSumOfNumbers(Node l1, Node l2) {
  int carry =0;
  
  Node newHead = null;
  Node tempNodeForIteration=null;
  int sum=0;

  int firstIter=0;
  while(l1!=null || l2!=null)
  {
   firstIter++;
   sum=carry;
   if(l1!=null)
   {
    sum=sum+l1.value;
    l1=l1.next;
   }

   if(l2!=null)
   {
    sum=sum+l2.value;
    l2=l2.next;
   }


   carry=sum/10;
   sum=sum%10;
   // Check if it first node for the result
   if(firstIter==1)
   { 
    tempNodeForIteration = new Node(sum);
    newHead=tempNodeForIteration;
   }
   else
   {
    Node tempSumNode=new Node(sum);
    tempNodeForIteration.next=tempSumNode;
    tempNodeForIteration=tempNodeForIteration.next;
   }
   
  }
  if(carry!=0)
  {
   Node tempNode=new Node(carry);
   tempNodeForIteration.next=tempNode;
  }
  return newHead;
 }

 public static void main(String[] args) {
  AddTwoNumberLinkedList list = new AddTwoNumberLinkedList();
  // Creating a linked list
  Node head1=new Node(5);
  list.addToTheLast(head1);
  list.addToTheLast(new Node(6));
  list.addToTheLast(new Node(7));
  list.addToTheLast(new Node(1));
  list.addToTheLast(new Node(2));
  System.out.print("Number 1:  ");
  list.printList(head1);
  head=null;
  Node head2=new Node(6);
  list.addToTheLast(head2);
      list.addToTheLast(new Node(3));
  list.addToTheLast(new Node(5));
  list.addToTheLast(new Node(9));
  
  System.out.print("Number 2:  ");
  list.printList(head2);
  // Reversing first linkedList
  head1=reverseLinkedList(head1);
 
  //Reversing second linkedList
  head2=reverseLinkedList(head2);
  
  // function to find sum of two linkedlist represent by number
  Node result= list.findSumOfNumbers(head1,head2);
  // Reverse the above linkedlist to get actual sum
  result=reverseLinkedList(result);
  System.out.print("Sum:  ");
  list.printList(result);
  
 }

}

When you run above program , you will get following output:
 
Number 1:  5 6 7 1 2 
Number 2:  6 3 5 9 
Sum:  6 3 0 7 1 
Please go through Frequently asked Interview programs in java  for more such programs.

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
This is 10th part of java binary tree tutorial.

In this post, we will see how to print vertical sum of binary tree nodes in java. Below diagram will show vertical sum for binary tree.


Algorithm:

Steps for print vertical sum of binary tree:
  • Traverse tree in inorder traversal.
  • Create a variable level and initialise it with 0. When you traverse left child, decrease level by 1(level--) and when you traverse right child, increase level by 1(level++).
  • We need to maintain TreeMap with key as level and value as node data. If you get same key(level) again, then you need to add current node data to previous stored value to calculate sum.
    For example:
    TreeMap has entry with (0,40) where 0 is level and 40 is node data. So while traversing, if you encountered node 30 at level 0, so after processing node 30, TreeMap will have entry as (0,70)
  • Once TreeMap is populated after iterating all nodes, print the results.
Code for recursion will be:
// prints vertical sum in binary tree
 public static void printVertivalSumOfBinaryTree(TreeNode startNode,TreeMap<Integer,Integer> treeNodeMap,int level) {
  if(startNode==null)
  {
   return;
  }
  
  // Decrease level by 1 when iterating left child
  printVertivalSumOfBinaryTree(startNode.left,treeNodeMap,level-1);
  
  if(treeNodeMap.get(level)!=null)
  {
         // Adding current node data to previous stored value to get the sum
       Integer sum=treeNodeMap.get(level)+startNode.data;
         treeNodeMap.put(level, sum);
  }
  else
  {
  
   treeNodeMap.put(level, startNode.data);
  }
 // Increase level by 1 when iterating left child
  printVertivalSumOfBinaryTree(startNode.right,treeNodeMap,level+1);
  
 }

Please find diagram below which shows level assigned for each binary tree node.

Example:

Lets create java program for printing vertical sum in binary tree:
 
 
package org.arpit.java2blog;

import java.util.Map.Entry;
import java.util.TreeMap;

public class BinaryTreeVerticalSumMain {

 
 public static class TreeNode
 {
  int data;
  TreeNode left;
  TreeNode right;
  TreeNode(int data)
  {
   this.data=data;
  }
 }
 
// prints vertical sum of binary tree
 public static void printVertivalSumOfBinaryTree(TreeNode startNode,TreeMap<Integer,Integer> treeNodeMap,int level) {
  if(startNode==null)
  {
   return;
  }
  
  // Decrease level by 1 when iterating left child
  printVertivalSumOfBinaryTree(startNode.left,treeNodeMap,level-1);
  
  if(treeNodeMap.get(level)!=null)
  {
   Integer sum=treeNodeMap.get(level)+startNode.data;
   // Adding current node data to previous stored value to get the sum
   treeNodeMap.put(level, sum);
  }
  else
  {
  
   treeNodeMap.put(level, startNode.data);
  }
 // Increase level by 1 when iterating left child
  printVertivalSumOfBinaryTree(startNode.right,treeNodeMap,level+1);
  
 }
 public static void main(String[] args)
 {
  BinaryTreeVerticalSumMain bi=new BinaryTreeVerticalSumMain();
  // Creating a binary tree
  TreeNode rootNode=createBinaryTree();
  System.out.println("Vertical sum of binary tree will be:");
  TreeMap<Integer,Integer> treeNodeMap=new TreeMap<Integer,Integer>();
  printVertivalSumOfBinaryTree(rootNode, treeNodeMap, 0);
  
 for(Entry<Integer,Integer> entry:treeNodeMap.entrySet())
  System.out.println(entry.getValue());
 }
 
 public static TreeNode createBinaryTree()
 {
  
  TreeNode rootNode =new TreeNode(40);
  TreeNode node20=new TreeNode(20);
  TreeNode node10=new TreeNode(10);
  TreeNode node30=new TreeNode(30);
  TreeNode node60=new TreeNode(60);
  TreeNode node50=new TreeNode(50);
  TreeNode node70=new TreeNode(70);
  TreeNode node55=new TreeNode(55);
  TreeNode node5=new TreeNode(5);
  
  rootNode.left=node20;
  rootNode.right=node60;
  
  node20.left=node10;
  node20.right=node30;
  
  node60.left=node50;
  node60.right=node70;
  node50.right=node55;
  node30.left=node5;
  return rootNode;
 }
}



Run above program and you will get following output:
 
Vertical sum of binary tree will be:
10
25
120
115
70
 

Java Binary tree tutorial:

    Binary tree in java Binary tree preorder traversal Binary tree postorder traversal Binary tree inorder traversal Binary tree level order traversal Binary tree spiral order traversal Binary tree reverse level order traversal Binary tree boundary traversal Print leaf nodes of binary tree Count leaf nodes in binary tree get maximum element in binary tree Print all paths from root to leaf in binary tree Print vertical sum of binary tree in java Get level of node in binary tree in java Lowest common ancestor(LCA) in binary tree in java
 

Java tutorial for beginners Copyright © 2012