Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct tree {
- int key;
- tree* left, * right;
- };
- tree* newNode(int val) {
- tree* newNode = new tree();
- newNode->key = val;
- newNode->left = newNode->right = NULL;
- return newNode;
- }
- tree* insertNode(tree* root, int val) {
- if (root == NULL)
- root = newNode(val);
- else if (val <= root->key)
- root->left = insertNode(root->left, val);
- else
- root->right = insertNode(root->right, val);
- return root;
- }
- void searchParent(tree* root, int val, int parent) {
- if (root == NULL)
- return;
- if (root->key == val)
- cout << parent;
- else {
- searchParent(root->left, val, root->key);
- searchParent(root->right, val, root->key);
- }
- }
- int main() {
- tree* root = NULL;
- int x, val1, val2;
- cout << "How many nodes to add to tree: ";
- cin >> x;
- for (int i = 0; i < x; i++) {
- cout << "Key for node " << i + 1 << ": ";
- cin >> val1;
- root = insertNode(root, val1);
- }
- cout << "Find parent of: ";
- cin >> val2;
- searchParent(root, val2, -1);
- return 0;
- }
Add Comment
Please, Sign In to add comment