Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- /* A binary tree node has key, pointer to left
- child and a pointer to right child */
- struct Node
- {
- int key;
- struct Node* left, *right;
- };
- /* To create a newNode of tree and return pointer */
- struct Node* newNode(int key)
- {
- Node* temp = new Node;
- temp->key = key;
- temp->left = temp->right = NULL;
- return (temp);
- }
- void print(vector<int>&v){
- int n=v.size();
- if(n==0)
- return;
- for(int i=0;i<v.size();i++){
- cout<<v[i]<<" ";
- }
- cout<<endl;
- }
- void printPaths(Node *root,vector<int>&v){
- if(root==NULL)
- return;
- v.push_back(root->key);
- if(root->left==NULL&&root->right==NULL){
- print(v);
- v.pop_back();
- return;
- }
- printPaths(root->left,v);
- printPaths(root->right,v);
- v.pop_back();
- }
- void printUP(Node *root,map<Node*,Node*>mp){
- if(root==NULL)
- return;
- printUP(mp[root],mp);
- cout<<root->key<<" ";
- }
- void printPathsIt(Node *root){
- if(root==NULL)
- return;
- stack<Node*>st;
- st.push(root);
- map<Node*,Node*>mp;
- mp[root]=NULL;
- while(!st.empty()){
- Node *temp=st.top();
- st.pop();
- if(!temp->left&&!temp->right){
- printUP(temp,mp);
- cout<<endl;
- continue;
- }
- if(temp->right){
- st.push(temp->right);
- mp[temp->right]=temp;
- }
- if(temp->left){
- st.push(temp->left);
- mp[temp->left]=temp;
- }
- }
- }
- void inorder(Node* root)
- {
- if (root)
- {
- inorder(root->left);
- printf("%d ", root->key);
- inorder(root->right);
- }
- }
- // Driver program to test above functions
- int main()
- {
- // Making above given diagram's binary tree
- Node* root = newNode(8);
- root->left = newNode(3);
- root->left->left = newNode(1);
- root->left->right = newNode(6);
- root->left->right->left = newNode(4);
- root->left->right->right = newNode(7);
- root->right = newNode(10);
- root->right->right = newNode(14);
- root->right->right->left = newNode(13);
- //inorder(root);
- vector<int>v;
- // printPaths(root,v);
- printPathsIt(root);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement