25 Dec 2013

Remove Leaf Nodes

Problem Statement:
        Remove the leaf nodes of the given binary tree.

                                                                   
Fig1: Given Binary Tree

Tree with leaves removed:


Solution:

Full Source Code: LINK

Code implementation:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
/**
  *Remove Leave Nodes 
  */
 public Node pruneLeaves(Node root){
  if(root.left== null && root.right==null)
   return null;
  else
  {
   if(root.left!=null)
   root.left = pruneLeaves(root.left);
   if(root.right!=null)
   root.right = pruneLeaves(root.right);
  }
  return root;
 }


Please Comment and post suggestions.
Happy Coding!! :)

No comments:

Post a Comment