Advertisement
dreadmachine

tree_min_height.cpp

Dec 10th, 2021
638
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <iostream>
  2. #include <climits>
  3. #include <algorithm>
  4.  
  5. class Tree {
  6. private:
  7.   struct TreeNode {
  8.     int val;
  9.     TreeNode *l, *r;
  10.     TreeNode(int val, TreeNode *l = nullptr, TreeNode *r = nullptr) :
  11.       val(val), l(l), r(r) {}
  12.   };
  13.   size_t size;
  14.   TreeNode *root;
  15.   TreeNode *__insert(TreeNode *root, TreeNode *node) {
  16.     if(!root)
  17.       return node;
  18.     if(node->val < root->val)
  19.       root->l = __insert(root->l, node);
  20.     else
  21.       root->r = __insert(root->r, node);
  22.     return root;
  23.   }
  24.   size_t __minimal_height(TreeNode *root, size_t current_height) {
  25.     if(!root->l && !root->r)
  26.       return current_height + 1;
  27.     if(!root->l) return __minimal_height(root->r, current_height + 1);
  28.     if(!root->r) return __minimal_height(root->l, current_height + 1);
  29.     return std::min(__minimal_height(root->l, current_height + 1),
  30.                     __minimal_height(root->r, current_height + 1));
  31.   }
  32. public:
  33.   Tree() : size(0), root(nullptr) {}
  34.   void insert(int val) {
  35.     root = __insert(root, new TreeNode(val));
  36.   }
  37.   size_t minimal_height() {
  38.     return __minimal_height(root, 0);
  39.   };
  40. };
  41.  
  42. int main() {
  43.   Tree t;
  44.   int val;
  45.   while(std::cin >> val) {
  46.     t.insert(val);
  47.   }
  48.   std::cout << t.minimal_height();
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement