In this c++ article i am going to explain how to print the nodes from root to leaf in binary tree .According to binary tree concept we need to traverse through the whole tree to print each path from root to leaf .In this program preorder traversal is used. There can be multiple paths and as it is wrote without recursion so it will be using stack and map concept
for example : different paths for the following binary tree : PATHS ARE BEEN MARKED BY RED
1. First the input will be binary tree.
after that current variable will traverse through the binary tree in which there will three conditions
3. case 1: if the current node has right node value then it will be stored in stack nodeStack1
4. case 2: if the current node has left node value then it will be stored in stack nodeStack1
5. case 3: if the current node doesn't have either right or left or both the nodes then the control will be shifted to printValues function where it push the elements from bottom to top and the print the values by poping out the top values .
Input is pre-defined if user want to change the values the user have to make changes in the program itself.
using namespace std;
struct Node *left, *right;
Node* new1(int data)
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
void printValues(Node* current, map<Node*, Node*> parent) ;
void traverse(Node* root) ;
Node* r1 = new1(68);
r1->left = new1(69);
r1->right = new1(92);
r1->left->left = new1(98);
r1->left->right = new1(20);
r1->right->left = new1(63);
void printValues(Node* current, map<Node*, Node*> parent)
current = parent[current];
current = s1.top();
cout << current->data << " ";
cout << endl;
void traverse(Node* root)
if (root == NULL)
map<Node*, Node*> parent;
parent[root] = NULL;
Node* current = nodeStack1.top();
parent[current->right] = current;
parent[current->left] = current;
if (!(current->left) && !(current->right))
In this example the input be binary tree which is given below:
- this binary tree will transferred to the traverse function "traverse(Node* root)"
- in this function the values of the binary tree are saved in the map "parent" according to the three cases .to store the values in the map "nodestack1" node is used.the values will be stored as shown below:
in this function printValues(Node* current, map<Node*, Node*> parent) there will be two while loops which we work as shown below :
- if the third condition is valid it will be going to print the values using the stack s1 using pusing and poping values from the stack.