Given a general tree with n nodes numbered from 1 to n and rooted at node 1,
the task is to print all possible paths from root to leaf nodes.
Examples :
Input :
1
/ \
2 3
/ \ / \
4 5 6 7
Output : {1, 2, 4} , {1, 2, 5} , {1, 3, 6} , {1, 3, 7} .
Explanation :
Clearly we can see all the possible paths from node 1 to every leaf
node.
Approach :
We will simply run dfs from node 1 and keep on pushing the encountered nodes into a vector,
and as soon as we reach to the leaf node , we will store that path.
Implementation :
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// utility function to add edge in the tree
void addEdge(vector<int> adj[], int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void dfs(int node, vector<int> adj[],
vector<vector<int> >& allPaths, vector<int> temp,
vector<int>& vis)
{
vis[node]=1;
// pushing encountered node in the temp vector
temp.push_back(node);
// flag variable to check if leaf node is reached or not
bool flag=false;
for(auto child:adj[node])
{
if(!vis[child])
{
// implies current child is not a leaf node
flag=true;
dfs(child,adj,allPaths,temp,vis);
}
}
// leaf node reached
// storing the encountered path
if(!flag)
allPaths.push_back(temp);
// removing last element
// to explore more paths
temp.pop_back();
}
void printAllPaths(vector<int> adj[], int n)
{
// 2-d vector to store all the root to leaf paths
vector<vector<int> > allPaths;
// vector to store individual path from root to leaf
vector<int> temp;
vector<int> vis(n + 1, 0);
// running dfs on node 1
dfs(1, adj, allPaths, temp, vis);
// printing every path
for (vector<int> path : allPaths) {
for (auto x : path)
cout << x << " ";
cout << "\n";
}
}
int main()
{
// number of nodes in the tree
int n = 7;
// adjacency list of the tree
vector<int> adj[n + 1];
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 2, 4);
addEdge(adj, 2, 5);
addEdge(adj, 3, 6);
addEdge(adj, 3, 7);
printAllPaths(adj, n);
return 0;
}