Advertisement
Viksy

Paths With A Given Sum

Mar 9th, 2022
1,212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1.     private List<Tree<E>> traverseTreeWithBfs(){
  2.         Deque<Tree<E>> queue = new ArrayDeque<>();
  3.  
  4.         queue.offer(this);
  5.  
  6.         List<Tree<E>> allNodes = new ArrayList<>();
  7.  
  8.         while(!queue.isEmpty()){
  9.             Tree<E> tree = queue.poll();
  10.  
  11.             allNodes.add(tree);
  12.  
  13.             for (Tree<E> child : tree.children) {
  14.                 queue.offer(child);
  15.             }
  16.         }
  17.  
  18.         return allNodes;
  19.     }
  20.  
  21.     private boolean isLeaf() {
  22.         return this.parent != null && this.children.size() == 0;
  23.     }
  24.  
  25.     @Override
  26.     public List<List<E>> pathsWithGivenSum(int sum) {
  27.         List<Tree<E>> trees = this.traverseTreeWithBfs();
  28.  
  29.         List<E> goodPath = new ArrayList<>();
  30.         List<List<E>> result = new ArrayList<>();
  31.  
  32.         int currentSum;
  33.  
  34.         for(Tree<E> tree : trees){
  35.             goodPath.clear();
  36.             currentSum = 0;
  37.  
  38.             if(tree.isLeaf()){
  39.                 while(tree.parent != null){
  40.                     currentSum += (Integer) tree.getKey();
  41.                     goodPath.add(tree.getKey());
  42.                     tree = tree.parent;
  43.                 }
  44.  
  45.                 currentSum += (Integer) tree.getKey();
  46.                 goodPath.add(tree.getKey());
  47.             }
  48.  
  49.             if(currentSum == sum){
  50.                 Collections.reverse(goodPath);
  51.                 result.add(goodPath);
  52.             }
  53.         }
  54.  
  55.         return result;
  56.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement