|
| 1 | +/* |
| 2 | +Time complexity: O(N) |
| 3 | +Auxiliary Space: O(N) |
| 4 | + |
| 5 | +*/ |
| 6 | +// Java program to print Longest Path |
| 7 | +// from root to leaf in a Binary tree |
| 8 | +import java.io.*; |
| 9 | +import java.util.ArrayList; |
| 10 | + |
| 11 | +class longestPathFromRootToLeafinBT { |
| 12 | + |
| 13 | + // Binary tree node |
| 14 | + static class Node { |
| 15 | + Node left; |
| 16 | + Node right; |
| 17 | + int data; |
| 18 | + }; |
| 19 | + |
| 20 | + // Function to create a new |
| 21 | + // Binary node |
| 22 | + // this can even be a constructor in above Node class |
| 23 | + static Node newNode(int data) { |
| 24 | + Node temp = new Node(); |
| 25 | + |
| 26 | + temp.data = data; |
| 27 | + temp.left = null; |
| 28 | + temp.right = null; |
| 29 | + |
| 30 | + return temp; |
| 31 | + } |
| 32 | + |
| 33 | + // Function to find and return the |
| 34 | + // longest path |
| 35 | + public static ArrayList<Integer> longestPath(Node root) { |
| 36 | + |
| 37 | + // If root is null means there |
| 38 | + // is no binary tree so |
| 39 | + // return a empty vector |
| 40 | + if (root == null) { |
| 41 | + ArrayList<Integer> output = new ArrayList<>(); |
| 42 | + return output; |
| 43 | + } |
| 44 | + |
| 45 | + // Recursive call on root.right |
| 46 | + ArrayList<Integer> right = longestPath(root.right); |
| 47 | + |
| 48 | + // Recursive call on root.left |
| 49 | + ArrayList<Integer> left = longestPath(root.left); |
| 50 | + |
| 51 | + // Compare the size of the two ArrayList |
| 52 | + // and insert current node accordingly |
| 53 | + if (right.size() < left.size()) { |
| 54 | + left.add(root.data); |
| 55 | + } else { |
| 56 | + right.add(root.data); |
| 57 | + } |
| 58 | + |
| 59 | + // Return the appropriate ArrayList |
| 60 | + return (left.size() > right.size() ? left : right); |
| 61 | + } |
| 62 | + |
| 63 | + // Driver Code |
| 64 | + public static void main(String[] args) { |
| 65 | + Node root = newNode(1); |
| 66 | + root.left = newNode(2); |
| 67 | + root.right = newNode(3); |
| 68 | + root.left.left = newNode(4); |
| 69 | + root.left.right = newNode(5); |
| 70 | + root.left.right.right = newNode(6); |
| 71 | + |
| 72 | + ArrayList<Integer> output = longestPath(root); |
| 73 | + int n = output.size(); |
| 74 | + |
| 75 | + System.out.print(output.get(n - 1)); |
| 76 | + for (int i = n - 2; i >= 0; i--) { |
| 77 | + System.out.print(" -> " + output.get(i)); |
| 78 | + } |
| 79 | + } |
| 80 | +} |
| 81 | + |
0 commit comments