Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to print the leaf nodes of a binary tree
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.util.*;
- // node class
- class node{
- int data;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- // function to print the leaf nodes of the binary tree
- static void print_leaves(node root){
- if (root != null){
- print_leaves(root.left);
- if(root.left == null && root.right == null){
- System.out.print(root.data + " ");
- }
- print_leaves(root.right);
- }
- }
- public static void main(String arg[]) {
- node head = new node(1);
- head.left = new node(2);
- head.right = new node(3);
- head.left.left = new node(4);
- head.left.right = new node(5);
- head.right.right = new node(6);
- head.left.left.right = new node(7);
- head.right.right.left = new node(8);
- head.left.left.right.left = new node(9);
- head.left.left.right.left.left = new node(10);
- head.right.right.left.right = new node(11);
- System.out.print("leaf nodes of the given tree are : ");
- print_leaves(head);
- }
- }
Add Comment
Please, Sign In to add comment