Print All Paths of a Tree Problem

Print All Paths of a Tree Problem

Given a binary tree, return all paths from root to leaf.

Example One

Input:

Output: [[1, 2, 4], [1, 2, 5], [1, 3, 6], [1, 3, 7]]

There are four leafs in the given graph, so we have four paths: from the root to every leaf. Each path is a list of the values from the tree nodes on the path, and we have four lists. They can go in any order.

Example Two

Input:

Output: [[10, 20, 40], [10, 20, 50], [10, 30]]

There are 3 paths in the tree.

The leftmost path contains values: 10 -> 20 -> 40

The rightmost path contains values: 10 -> 30

The other path contains values: 10 -> 20 -> 50

The order of the paths (order of the lists in the outer list) does not matter, so [[10, 30], [10, 20, 40], [10, 20, 50]] is another correct answer.

Notes

Input Parameters: Function has one argument, root of the input tree.

Output: Return a list of integer lists.

Constraints:

• 0

• -10^9

Solution

We provided one solution.

This problem asked to return all the paths from the root node to the leaf nodes. So, if there are K leaf nodes, there will be K paths. To find a path, we have used depth first search technique. The approach is described below:

a. If the root is null, there are no paths. Return empty list.

b. If the root node is also the only leaf node, return a list containing the root as a single path.

c. Append current node value in a temporary list and go to left child

d. If current node is a leaf node, append its value to the temporary list. Append the temporary list (the list itself, not its values) to the outer result list. Otherwise repeat step c. Remove current node value from the temporary list.

e. Go to the right child and repeat step c until you reach step d.

f. Remove current node value from the temporary list.

We did this using backtracking.

Time Complexity (assuming that input arguments are already

given and excluding time used in the declaration of output):

O(N+M) where N is the number of nodes and M is the number of edges.

As to print all the paths, we have to traverse the whole tree at least once and the tree contains N nodes and M edges, hence the computation complexity is O(N+M).

Time Complexity:

O((N+1)/2 log (N+1)) where N denotes the number of nodes in the tree.

Time complexity assuming that input arguments are already

given and excluding time used in the declaration of output is O(N + M) and to read input arguments it will take O( N+ M) time. Declaration of output takes O((N+1)/2 log (N+1)) times in worst case as if the input tree is a complete binary tree, there will be (N+1)/2 leaves and in each path there will be log N nodes. So, the size of the output list will be O((N+1)/2 log (N+1)). Hence time complexity will be O(N+M) + O(N+M) + O((N+1)/2 log (N+1)) → O((N+1)/2 log (N+1)).

Auxiliary Space:

O((N+1)/2 log (N+1)) where N denotes the number of nodes.

In the worst case, the size of the output list can be O((N+1)/2 log (N+1)) and recursion takes O(N) stack memory, auxiliary space is O((N+1)/2 log (N+1)) + O(N) → O((N+1)/2 log (N+1)).

Space Complexity:

O((N+1)/2 log (N+1)) where N denotes the number of nodes.

As to store input tree it will take O(N+ M) space, auxiliary

space is O((N+1)/2 log (N+1)) and to return the result it takes O((N+1)/2 log (N+1)) memory, hence space complexity is O(N+M) + O((N+1)/2 log (N+1)) + O((N+1)/2 log (N+1)) → O((N+1)/2 log (N+1)).


// -------- START --------

void getAllPaths(TreeNode *root, vector &currentPathValues, vector<vector > &allPaths){
    
    // If we reached at leaf node
    if(root->left_ptr == NULL && root->right_ptr == NULL){
       currentPathValues.push_back(root->val);
       allPaths.push_back(currentPathValues);
       currentPathValues.pop_back();
       return;
    }
    // Push current node's value in current path
    currentPathValues.push_back(root->val);

    // Recursive call for left subtree
    if(root->left_ptr != NULL){
        getAllPaths(root->left_ptr, currentPathValues, allPaths);
    }

    // Recusrive call for right subtree
    if(root->right_ptr != NULL){
        getAllPaths(root->right_ptr, currentPathValues, allPaths);
    }

    // Pop last added value i.e. current node's value
    currentPathValues.pop_back();
}

vector<vector > allPathsOfABinaryTree(TreeNode* root){
    vector<vector > allPaths;
    // empty or null tree check
    if(root == NULL) {
        return allPaths;
    }
    vector currentPathValue;
    getAllPaths(root, currentPathValue, allPaths);
    return allPaths;
}

// -------- END --------

IK courses Recommended

Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.

Fast filling course!

Get strategies to ace TPM interviews with training in program planning, execution, reporting, and behavioral frameworks.

Course covering SQL, ETL pipelines, data modeling, scalable systems, and FAANG interview prep to land top DE roles.

Course covering Embedded C, microcontrollers, system design, and debugging to crack FAANG-level Embedded SWE interviews.

Nail FAANG+ Engineering Management interviews with focused training for leadership, Scalable System Design, and coding.

End-to-end prep program to master FAANG-level SQL, statistics, ML, A/B testing, DL, and FAANG-level DS interviews.

Select a course based on your goals

Agentic AI

Learn to build AI agents to automate your repetitive workflows

Switch to AI/ML

Upskill yourself with AI and Machine learning skills

Interview Prep

Prepare for the toughest interviews with FAANG+ mentorship

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary