Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to print all the paths from root to leaf nodes in a binary tree
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.io.*;
- import java.lang.reflect.Array;
- import java.util.*;
- import static java.lang.Integer.max;
- // 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 all paths from root to leaf using recursive preorder traversal
- static void all_paths_from_root_to_leaf(node current, ArrayList<Integer> path){
- if(current == null){
- return;
- }
- // push the current node data into the path vector
- path.add(current.data);
- // if the current node is the leaf node then we print the path and return
- if(current.left == null && current.right == null){
- System.out.println(path);
- path.remove(path.size() - 1);
- return;
- }
- // else we traverse deeper into the binary tree in preorder fashion
- else{
- all_paths_from_root_to_leaf(current.left, path);
- all_paths_from_root_to_leaf(current.right, path);
- path.remove(path.size() - 1);
- }
- }
- 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.println("All paths from the root node to the leaf nodes are : ");
- all_paths_from_root_to_leaf(head, new ArrayList<Integer>());
- }
- }
Add Comment
Please, Sign In to add comment