Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Program to print all paths from root to leaf using recursive preorder traversal
- #include <iostream>
- using namespace std;
- // node class
- class node{
- public:
- int data;
- int hd;
- node* left;
- node* right;
- };
- // function that returns a pointer to new node
- node* createNode(int element){
- node* temp = (node*) malloc(sizeof(node));
- temp->data = element;
- temp->hd = -1;
- temp->left = NULL;
- temp->right = NULL;
- return temp;
- }
- // function to print the path vector
- void printPath(vector<int> path){
- for(int i=0; i<path.size(); i++){
- cout<<path[i]<<" ";
- }
- cout<<endl;
- }
- // function to print all paths from root to leaf using recursive preorder traversal
- void all_paths_from_root_to_leaf(node* current, vector<int> path){
- if(current == NULL){
- return;
- }
- // push the current node data into the path vector
- path.push_back(current->data);
- // if the current node is the leaf node then we print the path and return
- if(current->left == NULL && current->right == NULL){
- printPath(path);
- return;
- }
- // else we traverse deeper into the binary tree in preorder fashion
- else{
- all_paths_from_root_to_leaf(current->left, path);
- all_paths_from_root_to_leaf(current->right, path);
- }
- }
- int main() {
- node* head = createNode(1);
- head->left = createNode(2);
- head->right = createNode(3);
- head->left->left = createNode(4);
- head->left->right = createNode(5);
- head->right->right = createNode(6);
- head->left->left->right = createNode(7);
- head->right->right->left = createNode(8);
- head->left->left->right->left = createNode(9);
- head->left->left->right->left->left = createNode(10);
- head->right->right->left->right = createNode(11);
- cout<<"All the paths from root to the leaf nodes are : "<<endl;
- vector<int> s;
- all_paths_from_root_to_leaf(head,s);
- }
- /*
- All the paths from root to the leaf nodes are :
- 1 2 4 7 9 10
- 1 2 5
- 1 3 6 8 11
- Process finished with exit code 0
- */
Add Comment
Please, Sign In to add comment