top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to print leaf nodes of a binary tree?

+2 votes
329 views

How to print leaf nodes of a binary tree? Sample code in C/C++ would be helpful?

posted Jan 27, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

0 votes

The logic here is simple. Recursively go through left and then right elements, when the base condition is met (i.e, when r==null), add a check to see if the node’s left and right wings are null and if they are null print the value of the node.
Input binary search tree:
enter image description here

// print leaf nodes
public void leafNodes(BinaryNode r) {
    if(r!= null) {
        leafNodes(r.left);
        leafNodes(r.right);

        if(r.left == null && r.right == null) {
            System.out.println(r.element);
        }
    }
}

Note: This logic is same is recursive post order traversal, but instead of just printing the node value after left&right traversals we check to see if left&right children are null and then print the node value.

answer Jan 28, 2016 by Manikandan J
0 votes

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:

// print leaf nodes  
public static void printLeafNodes(TreeNode node) {  

  if(node==null)  
   return;  

  if(node.left == null && node.right == null) {  
   System.out.printf("%d ",node.data);  
  }  
  printLeafNodes(node.left);  
  printLeafNodes(node.right);  
}  
answer Jan 28, 2016 by Karthick.c
0 votes

public static void printLeafNodes(BinaryNode t)
{
if(t == NULL)
return;
if(t.left == NULL && t.right==NULL)
System.out.println(t.element);
else if(t.left != NULL && t.right == NULL)
printLeafNodes(t.left);

   else 
         printLeafNodes(t.right);      

}
void printLeafNodes(BinaryTreeNode* treePtr) {
if(treePtr.leftChild == null && treePtr.rightChild == null) {
//This is a leaf node; print its value
} else {
//Recurse on right subtree
if(treePtr.rightChild != null) {
printLeafNodes(treePtr.rightChild);
}
//Recurse on left subtree
if(treePtr.leftChild != null) {
printLeafNodes(treePtr.leftChild);
}
}
}

answer Feb 11, 2016 by Gunjan Saraswat
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...