|
| 1 | +/* |
| 2 | +For a given Binary Tree of type integer and a number K, print out all root-to-leaf paths where the sum of all the node data along the path is equal to K. |
| 3 | + |
| 4 | +Input Format: |
| 5 | +The first line of input will contain the node data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data. |
| 6 | +The second line of input contains an integer value K. |
| 7 | + |
| 8 | +Output Format: |
| 9 | +Lines equal to the total number of paths will be printed. All the node data in every path will be printed in a linear fashion taken in the order they appear from top to down bottom in the tree. A single space will separate them all. |
| 10 | + |
| 11 | +Constriants: |
| 12 | +1 <= N <= 10^5 |
| 13 | +0 <= K <= 10^8 |
| 14 | +Where N is the total number of nodes in the binary tree. |
| 15 | +Time Limit: 1 second |
| 16 | + |
| 17 | +Sample Input 1: |
| 18 | +2 3 9 4 8 -1 2 4 -1 -1 -1 6 -1 -1 -1 -1 -1 |
| 19 | +13 |
| 20 | +Sample Output 1: |
| 21 | +2 3 4 4 |
| 22 | +2 3 8 |
| 23 | + |
| 24 | +Sample Input 2: |
| 25 | +5 6 7 2 3 -1 1 -1 -1 -1 9 -1 -1 -1 -1 |
| 26 | +13 |
| 27 | +Sample Output 2: |
| 28 | +5 6 2 |
| 29 | +5 7 1 |
| 30 | +*/ |
| 31 | + |
| 32 | +import java.util.*; |
| 33 | +/* |
| 34 | + |
| 35 | + Following is the structure used to represent the Binary Tree Node |
| 36 | + |
| 37 | + class BinaryTreeNode<T> { |
| 38 | + T data; |
| 39 | + BinaryTreeNode<T> left; |
| 40 | + BinaryTreeNode<T> right; |
| 41 | + |
| 42 | + public BinaryTreeNode(T data) { |
| 43 | + this.data = data; |
| 44 | + this.left = null; |
| 45 | + this.right = null; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | +*/ |
| 50 | + |
| 51 | +public class Solution { |
| 52 | + |
| 53 | + public static void rootToLeafPathsSumToK(BinaryTreeNode<Integer> root, int k) { |
| 54 | + //Your code goes here |
| 55 | + String arr=""; |
| 56 | + rootToLeafPathsSumToK(root,k,arr); |
| 57 | + } |
| 58 | + |
| 59 | + public static void rootToLeafPathsSumToK(BinaryTreeNode<Integer> root, int k,String arr) |
| 60 | + { |
| 61 | + if (root==null) |
| 62 | + { |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + int rootData=root.data; |
| 67 | + //System.out.println("Root data: "+rootData); |
| 68 | + //System.out.println("k: "+k); |
| 69 | + //System.out.println("Old Arraylist: "+arr); |
| 70 | + arr=arr+rootData+" "; |
| 71 | + if(k==rootData && root.left==null && root.right==null) |
| 72 | + { |
| 73 | + //System.out.print("Path found: "); |
| 74 | + //for (int i=0;i<arr.length();i++) |
| 75 | + //System.out.print(arr.charAt(i)+" "); |
| 76 | + //System.out.println(); |
| 77 | + System.out.println(arr); |
| 78 | + return; |
| 79 | + } |
| 80 | + //System.out.println(); |
| 81 | + |
| 82 | + rootToLeafPathsSumToK(root.left,k-rootData,arr); |
| 83 | + rootToLeafPathsSumToK(root.right,k-rootData,arr); |
| 84 | + } |
| 85 | + |
| 86 | +} |
0 commit comments