m2skills

all paths java

Jun 1st, 2018
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.09 KB | None | 0 0
  1. // http://code2begin.blogspot.com
  2. // program to print all the paths from root to leaf nodes in a binary tree
  3.  
  4. /**
  5.  * Created by MOHIT on 25-05-2018.
  6.  */
  7.  
  8. import java.io.*;
  9. import java.lang.reflect.Array;
  10. import java.util.*;
  11.  
  12. import static java.lang.Integer.max;
  13.  
  14.  
  15. // node class
  16. class node{
  17.     int data;
  18.     node left;
  19.     node right;
  20.  
  21.     // function that returns a pointer to new node
  22.     public node(int element){
  23.         this.data = element;
  24.         this.left = null;
  25.         this.right = null;
  26.        
  27.     }
  28. };
  29.  
  30.  
  31. public class BinaryTree {
  32.  
  33.     // function to print all paths from root to leaf using recursive preorder traversal
  34.     static void all_paths_from_root_to_leaf(node current, ArrayList<Integer> path){
  35.         if(current == null){
  36.             return;
  37.         }
  38.         // push the current node data into the path vector
  39.         path.add(current.data);
  40.  
  41.         // if the current node is the leaf node then we print the path and return
  42.         if(current.left == null && current.right == null){
  43.             System.out.println(path);
  44.             path.remove(path.size() - 1);
  45.             return;
  46.         }
  47.         // else we traverse deeper into the binary tree in preorder fashion
  48.         else{
  49.             all_paths_from_root_to_leaf(current.left, path);
  50.             all_paths_from_root_to_leaf(current.right, path);
  51.             path.remove(path.size() - 1);
  52.         }
  53.     }
  54.    
  55.  
  56.     public static void main(String arg[]) {
  57.         node head = new node(1);
  58.         head.left = new node(2);
  59.         head.right = new node(3);
  60.         head.left.left = new node(4);
  61.         head.left.right = new node(5);
  62.         head.right.right = new node(6);
  63.         head.left.left.right = new node(7);
  64.         head.right.right.left = new node(8);
  65.         head.left.left.right.left = new node(9);
  66.         head.left.left.right.left.left = new node(10);
  67.         head.right.right.left.right = new node(11);
  68.         System.out.println("All paths from the root node to the leaf nodes are : ");
  69.         all_paths_from_root_to_leaf(head, new ArrayList<Integer>());
  70.     }
  71. }
Add Comment
Please, Sign In to add comment