KatInterview

955. Complete Binary Tree Inserter

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Level-Order Traversal with Array Storage

This approach leverages the properties of a complete binary tree. The key idea is to represent the tree using an array (or a list/vector) that stores nodes in level-order. This is analogous to the array-based representation of a heap.

Solution

Complete Binary Tree Inserter in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from collections import deque
from typing import Optional

class CBTInserter:

    def __init__(self, root: Optional[TreeNode]):
        self.root = root
        self.tree = []
        if not root:
            return
        
        # Use BFS to populate the tree list in level-order.
        q = deque([root])
        while q:
            node = q.popleft()
            self.tree.append(node)
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)

    def insert(self, val: int) -> int:
        # The new node will be at the next available position, which is len(self.tree).
        n = len(self.tree)
        newNode = TreeNode(val)
        
        # Find the parent. For a node at index n, its parent is at (n-1)//2.
        parent = self.tree[(n - 1) // 2]
        
        # Attach the new node as a left or right child.
        if not parent.left:
            parent.left = newNode
        else:
            parent.right = newNode
            
        # Add the new node to our level-order list.
        self.tree.append(newNode)
        
        return parent.val

    def get_root(self) -> Optional[TreeNode]:
        return self.root


# Your CBTInserter object will be instantiated and called as such:
# obj = CBTInserter(root)
# param_1 = obj.insert(val)
# param_2 = obj.get_root()

Complete Binary Tree Inserter in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
import java.util.Queue;
import java.util.LinkedList;
import java.util.List;
import java.util.ArrayList;

class CBTInserter {
    private TreeNode root;
    private List<TreeNode> tree;

    public CBTInserter(TreeNode root) {
        this.root = root;
        this.tree = new ArrayList<>();
        if (root == null) return;
        
        // Use BFS to populate the tree list in level-order.
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        
        while (!q.isEmpty()) {
            TreeNode node = q.poll();
            tree.add(node);
            if (node.left != null) {
                q.offer(node.left);
            }
            if (node.right != null) {
                q.offer(node.right);
            }
        }
    }
    
    public int insert(int val) {
        // The new node will be at the next available position, which is tree.size().
        int n = tree.size();
        TreeNode newNode = new TreeNode(val);
        
        // Find the parent. For a node at index n, its parent is at (n-1)/2.
        TreeNode parent = tree.get((n - 1) / 2);
        
        // Attach the new node as a left or right child.
        if (parent.left == null) {
            parent.left = newNode;
        } else {
            parent.right = newNode;
        }
        
        // Add the new node to our level-order list.
        tree.add(newNode);
        
        return parent.val;
    }
    
    public TreeNode get_root() {
        return this.root;
    }
}

/**
 * Your CBTInserter object will be instantiated and called as such:
 * CBTInserter obj = new CBTInserter(root);
 * int param_1 = obj.insert(val);
 * TreeNode param_2 = obj.get_root();
 */

Complete Binary Tree Inserter in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <vector>
#include <queue>

class CBTInserter {
private:
    TreeNode* root_node;
    std::vector<TreeNode*> tree;

public:
    CBTInserter(TreeNode* root) {
        this->root_node = root;
        if (!root) return;

        // Use BFS to populate the tree vector in level-order.
        std::queue<TreeNode*> q;
        q.push(root);

        while (!q.empty()) {
            TreeNode* node = q.front();
            q.pop();
            tree.push_back(node);
            if (node->left) {
                q.push(node->left);
            }
            if (node->right) {
                q.push(node->right);
            }
        }
    }
    
    int insert(int val) {
        // The new node will be at the next available position, which is tree.size().
        int n = tree.size();
        TreeNode* newNode = new TreeNode(val);
        
        // Find the parent. For a node at index n, its parent is at (n-1)/2.
        TreeNode* parent = tree[(n - 1) / 2];
        
        // Attach the new node as a left or right child.
        if (!parent->left) {
            parent->left = newNode;
        } else {
            parent->right = newNode;
        }
        
        // Add the new node to our level-order list.
        tree.push_back(newNode);
        
        return parent->val;
    }
    
    TreeNode* get_root() {
        return root_node;
    }
};

/**
 * Your CBTInserter object will be instantiated and called as such:
 * CBTInserter* obj = new CBTInserter(root);
 * int param_1 = obj->insert(val);
 * TreeNode* param_2 = obj->get_root();
 */

Complete Binary Tree Inserter in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

class CBTInserter {
    private rootNode: TreeNode | null;
    private tree: TreeNode[];

    constructor(root: TreeNode | null) {
        this.rootNode = root;
        this.tree = [];
        if (!root) {
            return;
        }

        // Use BFS to populate the tree list in level-order.
        // Using an index pointer `head` to simulate a queue for O(N) performance.
        const q: TreeNode[] = [root];
        let head = 0;
        while (head < q.length) {
            const node = q[head++];
            this.tree.push(node);
            if (node.left) {
                q.push(node.left);
            }
            if (node.right) {
                q.push(node.right);
            }
        }
    }

    insert(val: number): number {
        // The new node will be at the next available position, which is this.tree.length.
        const n = this.tree.length;
        const newNode = new TreeNode(val);
        
        // Find the parent. For a node at index n, its parent is at floor((n-1)/2).
        const parentIndex = Math.floor((n - 1) / 2);
        const parent = this.tree[parentIndex];
        
        // Attach the new node as a left or right child.
        if (!parent.left) {
            parent.left = newNode;
        } else {
            parent.right = newNode;
        }
        
        // Add the new node to our level-order list.
        this.tree.push(newNode);
        
        return parent.val;
    }

    get_root(): TreeNode | null {
        return this.rootNode;
    }
}

/**
 * Your CBTInserter object will be instantiated and called as such:
 * var obj = new CBTInserter(root)
 * var param_1 = obj.insert(val)
 * var param_2 = obj.get_root()
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.