Advertisement
zhukov000

BST, pointers, not balanced

Dec 28th, 2019
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Node
  5. {
  6.   int key;
  7.   Node * left, * right;
  8.   Node(int pkey): key(pkey), left(nullptr), right(nullptr) {}
  9. };
  10.  
  11. Node * root = nullptr;
  12.  
  13. bool exists(Node * node, const int & key)
  14. {
  15.   if (node == nullptr) return false;
  16.   if (node->key == key) return true;
  17.   return exists(node->left, key) || exists(node->right, key);
  18. }
  19.  
  20. void insert(Node * &node, const int & key)
  21. {
  22.   if ( !node ) node = new Node(key);
  23.   else
  24.   {
  25.     if ( key < node->key )
  26.       insert(node->left, key);
  27.     if ( key > node->key )
  28.       insert(node->right, key);
  29.   }
  30. }
  31.  
  32. int depth(Node * node)
  33. {
  34.   if (!node) return 0;
  35.   return max(depth(node->left), depth(node->right)) + 1;
  36. }
  37.  
  38. int main()
  39. {
  40.   ios_base::sync_with_stdio(0);
  41.   cin.tie(0);
  42.   cout.tie(0);
  43.   // freopen("input.txt", "r", stdin);
  44.   int x;
  45.   while (true)
  46.   {
  47.     cin >> x;
  48.     if(!x) break;
  49.     insert(root, x);
  50.   }
  51.   cout << depth(root);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement