AleksandarH

Y1S2 Find Parent in Binary Tree Homework

May 21st, 2021 (edited)
371
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct tree {
  5.     int key;
  6.     tree* left, * right;
  7. };
  8.  
  9. tree* newNode(int val) {
  10.     tree* newNode = new tree();
  11.     newNode->key = val;
  12.     newNode->left = newNode->right = NULL;
  13.     return newNode;
  14. }
  15.  
  16. tree* insertNode(tree* root, int val) {
  17.     if (root == NULL)
  18.         root = newNode(val);
  19.     else if (val <= root->key)
  20.         root->left = insertNode(root->left, val);
  21.     else
  22.         root->right = insertNode(root->right, val);
  23.     return root;
  24. }
  25.  
  26. void searchParent(tree* root, int val, int parent) {
  27.     if (root == NULL)
  28.         return;
  29.     if (root->key == val)
  30.         cout << parent;
  31.     else {
  32.         searchParent(root->left, val, root->key);
  33.         searchParent(root->right, val, root->key);
  34.     }
  35. }
  36.  
  37. int main() {
  38.     tree* root = NULL;
  39.     int x, val1, val2;
  40.     cout << "How many nodes to add to tree: ";
  41.     cin >> x;
  42.     for (int i = 0; i < x; i++) {
  43.         cout << "Key for node " << i + 1 << ": ";
  44.         cin >> val1;
  45.         root = insertNode(root, val1);
  46.     }
  47.     cout << "Find parent of: ";
  48.     cin >> val2;
  49.     searchParent(root, val2, -1);
  50.     return 0;
  51. }
Add Comment
Please, Sign In to add comment