//
// main.cpp
// Ancestors of a node
//
// Created by Himanshu on 15/09/21.
//
#include <iostream>
#include <queue>
using namespace std;
struct node {
int info = 0;
struct node *left, *right;
};
typedef struct node Node;
node* newNode(int data)
{
node* Node = new node();
Node->info = data;
Node->left = NULL;
Node->right = NULL;
return(Node);
}
bool ancestor (Node *root, int key) {
if (!root) {
return false;
} else if (root->info == key) {
return true;
}
if ((ancestor (root->left, key)) || (ancestor (root->right, key))) {
cout<<(root->info)<<" ";
return true;
}
return false;
}
int main() {
Node *root = newNode(1);
root->left = newNode(20);
root->right = newNode(21);
root->right->left = newNode(30);
root->right->right = newNode(31);
root->right->right->left = newNode(40);
root->right->right->left->right = newNode(51);
cout<<"The ancestors of 30 are: "<<endl;
ancestor(root, 30);
cout<<endl;
cout<<"The ancestors of 51 are: "<<endl;
ancestor(root, 51);
cout<<endl;
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBBbmNlc3RvcnMgb2YgYSBub2RlCi8vCi8vICBDcmVhdGVkIGJ5IEhpbWFuc2h1IG9uIDE1LzA5LzIxLgovLwoKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8cXVldWU+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgpzdHJ1Y3Qgbm9kZSB7CiAgICBpbnQgaW5mbyA9IDA7CiAgICBzdHJ1Y3Qgbm9kZSAqbGVmdCwgKnJpZ2h0Owp9Owp0eXBlZGVmIHN0cnVjdCBub2RlIE5vZGU7Cgpub2RlKiBuZXdOb2RlKGludCBkYXRhKQp7CiAgICBub2RlKiBOb2RlID0gbmV3IG5vZGUoKTsKICAgIE5vZGUtPmluZm8gPSBkYXRhOwogICAgTm9kZS0+bGVmdCA9IE5VTEw7CiAgICBOb2RlLT5yaWdodCA9IE5VTEw7CiAKICAgIHJldHVybihOb2RlKTsKfQoKCmJvb2wgYW5jZXN0b3IgKE5vZGUgKnJvb3QsIGludCBrZXkpIHsKICAgIGlmICghcm9vdCkgewogICAgICAgIHJldHV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