ANIKET KUMAR - CS126 - Algorithm Design & Implementation-5thSem-2022 - Print All Paths To Leaves and Their Details of A Binary Tree
ANIKET KUMAR - CS126 - Algorithm Design & Implementation-5thSem-2022 - Print All Paths To Leaves and Their Details of A Binary Tree
LAB MANUAL
Email [email protected]
u.in
Faculty Incharge
______________
Department of CSE Lab Manual: CS126 - Algorithm Design & Implementation-5thSem-2022
Aim: Print all paths to leaves and their details of a binary tree
Given a binary tree print all paths from root node to leaf nodes with their respective lengths
and total number of paths in it.
The root node of binary tree is given to you. A path from root to leaf in a tree is a sequence
of adjacent nodes from root to any leaf node.
Do not write the whole program, just complete the function void printAllPaths(Node root)
which takes the address of the root as a parameter and print all details as shown below.
Note: If the tree is empty, do not print anything.
Input Format
First line contains an integer N, denoting the number of integers to follow in the serialized
representation of the tree.
Second line contains N space separated integers, denoting the level order description of left
and right child of nodes, where -1 signifies a NULL child.
Output
For each test case, print the paths with their length and total paths in new lines.
Constraints
0 <= N <= 10^5
0 <= node data <= 1000
Sample Input
1
/\
2 3
/\ /
4 56
Sample Output
1242
1252
1362
3
Explanation:
First path is from 1 to 4 having 2 edges, so 1 2 4 is path and 2 is length of it.
Similarly for other two leaf nodes. And at last line total number of paths are printed.
Solution:
/*
* struct Node {
* int data;
* Node *left, *right;
* };
*
* The above structure defines a tree node.
*/
void findAllPath(Node* root, vector<int>temp, vector<vector<int>>&ans)
{
if(!root) return;
temp.push_back(root->data);
if(!root->left && !root->right)
{
ans.push_back(temp);
}
ANIKET KUMAR
2 [email protected]
Department of CSE Lab Manual: CS126 - Algorithm Design & Implementation-5thSem-2022
ANIKET KUMAR
3 [email protected]