Complete Binary Tree Inserter in C++

C++Server Side ProgrammingProgramming

As we know a complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. We have to write a data structure CBTInserter that is initialized with a complete binary tree and it supports the following operations−

  • CBTInserter(TreeNode root) this initializes the data structure on a given tree with head node root;

  • CBTInserter.insert(int v) this will used to insert a TreeNode into the tree with value node.val = v so that the tree remains complete, and returns the value of the parent of the inserted TreeNode;

  • CBTInserter.get_root() this will return the head node of the tree.

So for example, if we initialize the tree as [1,2,3,4,5,6], then insert 7 and 8, then try to get the tree, the output will be: 3, 4,[1,2,3,4,5,6,7,8], the 3 is because 7 will be inserted under 3, and 4 is because 8 will be inserted under 4.

To solve this, we will follow these steps −

  • Define a queue q, and a root

  • The initializer will take the full binary tree, then work as follows

  • set root as given root, insert root into the q

  • while true −

    • if left of root is present, then insert left of root into q, otherwise break the loop

    • if right of root is present, then insert right of root into q and delete front node from q, otherwise break the loop

  • From the insert method, it will take the value v

  • set parent := front element of q, temp := new node with value v, and insert it into q

  • if left of parent is not present, then set left of parent := temp otherwise delete front element from q, and insert temp as right child of parent

  • return the value of parent

  • from the getRoot() method, return the root

Example

Let us see the following implementation to get better understanding −

class CBTInserter {
   public:
   queue <TreeNode*> q;
   TreeNode* root;
   CBTInserter(TreeNode* root) {
      this->root = root;
      q.push(root);
      while(1){
         if(root->left){
            q.push(root->left);
         }
         else break;
         if(root->right){
            q.push(root->right);
            q.pop();
            root = q.front();
         }
         else break;
      }
   }
   int insert(int v) {
      TreeNode* parent = q.front();
      TreeNode* temp = new TreeNode(v);
      q.push(temp);
      if(!parent->left){
         parent->left = temp;
      } else {
         q.pop();
         parent->right = temp;
      }
      return parent->val;
   }
   TreeNode* get_root() {
      return root;
   }
};

Input

["CBTInserter","insert","insert","get_root"]
[[[1,2,3,4,5,6]],[7],[8],[]]

Output

[null,3,4,[1,2,3,4,5,6,7,8]]
raja
Published on 17-Mar-2020 06:37:33
Advertisements