tree_ancestor.cpp
// Iterative Function to print all ancestors of a given key
Iterative Function to print all ancestors of a given key
Iterative Function to print all ancestors of a given key
void printAncestors(struct Node *root, int key)
{
    stack<Node*> v;
    while(true){
        while(root and root->data != key){
            v.push(root);
            root = root->left;
        }
        if(v.empty() or (root and root->data == key))
            break;
        root = v.top();
        if(!root->right){
            v.pop();
            while(!v.empty() and v.top()->right == root){
                root = v.top();
                v.pop();
            }
        }
        root = (v.empty()) ? nullptr : v.top()->right;
    }
    while(!v.empty()){
        cout << v.top()->data << " ";
        v.pop();
    }
    cout << endl;
}
void printAncestors ( struct Node * root , int key ) { stack < Node * > v ; while ( true ) { while ( root and root -> data != key ) { v . push ( root ) ; root = root -> left ; } if ( v . empty ( ) or ( root and root -> data == key ) ) break ; root = v . top ( ) ; if ( ! root -> right ) { v . pop ( ) ; while ( ! v . empty ( ) and v . top ( ) -> right == root ) { root = v . top ( ) ; v . pop ( ) ; } } root = ( v . empty ( ) ) ? nullptr : v . top ( ) -> right ; } while ( ! v . empty ( ) ) { cout << v . top ( ) -> data << " " ; v . pop ( ) ; } cout << endl ; }
Iterative Function to print all ancestors of a given key
Iterative Function to print all ancestors of a given key