Question:
How to print all the paths from the root with a specified sum using Java

Summary

Let’s assume:

Sum- S

Input tree

1

       /   \

     20      3

           /    \

         4       15   

        /  \     /  \

       6    7   8    9 


Function- printPaths()


Solution

//User function Template for Java


/*Tree Node

class Node {

    int data;

    Node left;

    Node right;

    Node(int data) {

        this.data = data;

        left = null;

        right = null;

    }

*/


class Solution

{

    public static void dfs(Node root, int sum, ArrayList> ans, ArrayList curr) {

        

        if(root == null) return;

        curr.add(root.data);

        sum -= root.data;

        dfs(root.left, sum, ans, curr);

        dfs(root.right, sum, ans, curr);

        if(sum == 0) {

            ans.add(new ArrayList<>(curr));

        }

        sum += root.data;

        curr.remove(curr.size()-1);

    }

/*

35 16

13 10

16 19

5 33

5 28

33 22

2 28

3 8

26 27

25 28

7 12

31 12

25 1

10 1

29 23

8 3

12 11

*/

    public static ArrayList> printPaths(Node root, int sum)

    {

        // code here

        ArrayList> ans = new ArrayList<>();

        dfs(root, sum, ans, new ArrayList());

        return ans;

    }

}


Suggested blogs:

>Build a minimal ASP.Net Core API with Android Studio for Mac

>Build an Electron application from scratch

>Build Progressive Web Apps with Angular

>Building a web application with Angular and Firebase

>Building Web API using ASP.NET (C#)

>Built Web API using ASP.NET (C#)


Nisha Patel

Nisha Patel

Submit
0 Answers