Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private List<Tree<E>> traverseTreeWithBfs(){
- Deque<Tree<E>> queue = new ArrayDeque<>();
- queue.offer(this);
- List<Tree<E>> allNodes = new ArrayList<>();
- while(!queue.isEmpty()){
- Tree<E> tree = queue.poll();
- allNodes.add(tree);
- for (Tree<E> child : tree.children) {
- queue.offer(child);
- }
- }
- return allNodes;
- }
- private boolean isLeaf() {
- return this.parent != null && this.children.size() == 0;
- }
- @Override
- public List<List<E>> pathsWithGivenSum(int sum) {
- List<Tree<E>> trees = this.traverseTreeWithBfs();
- List<E> goodPath = new ArrayList<>();
- List<List<E>> result = new ArrayList<>();
- int currentSum;
- for(Tree<E> tree : trees){
- goodPath.clear();
- currentSum = 0;
- if(tree.isLeaf()){
- while(tree.parent != null){
- currentSum += (Integer) tree.getKey();
- goodPath.add(tree.getKey());
- tree = tree.parent;
- }
- currentSum += (Integer) tree.getKey();
- goodPath.add(tree.getKey());
- }
- if(currentSum == sum){
- Collections.reverse(goodPath);
- result.add(goodPath);
- }
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement