leetcode 919. Complete Binary Tree Inserter

If you are familiar with both heap and complete binary tree, you'll find them much the same in finding parent.
Mark from tree node with index 1, and the subsequent layer of nods with 2, 3, and the next layer 4,5,6,7, you'll find that node with index x's parent is node with index x/2.
So the naive solution is to keep an index-treenode map and the current size. When adding new node, the node will acquire index size + 1, thus we can find it's parent, which is node with index (size + 1) / 2.
Below is the naive solution.

class CBTInserter {

    int size = 0;
    TreeNode r = null;
    Map<Integer, TreeNode> m;
    public CBTInserter(TreeNode root) {
        this.r = root;
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.add(root);
        this.size = 1;
        m = new HashMap<>();
        m.put(1, root);
        while (!q.isEmpty()) {
            TreeNode node = q.poll();
            if (node != root) {
                insert(node.val);
            }
            if (node.left != null) q.add(node.left);
            if (node.right != null) q.add(node.right);
        }
    }
    
    public int insert(int v) {
        this.size += 1;
        int p = size / 2;
        TreeNode parent = m.get(p);
        TreeNode nn = new TreeNode(v);
        if (size % 2 == 0) {
            parent.left = nn;
        }
        else {
            parent.right = nn;
        }
        m.put(this.size, nn);
        return parent.val;
    }
    
    public TreeNode get_root() {
        return this. r;
    }
}

And we can do a little space improvement on code above. We can use a queue to keep the potential parent nodes.
But why a little, cause if the space complexity above is O(N) (N is the number of nodes), the space complexity below will be O(N/2) (and don't answer like this in your interview, your interview will not like it.....).
As for why, you can figure it out yourself.
The little improvement code is like

class CBTInserter {

    Queue<TreeNode> q;
    TreeNode root;
    public CBTInserter(TreeNode root) {
        q = new LinkedList<TreeNode>();
        Queue<TreeNode> tq = new LinkedList<TreeNode>();
        this.root = root;
        tq.add(root);
        q.add(root);
        while (!tq.isEmpty()) {
            TreeNode node = tq.poll();
            if (node != root) {
                insert(node.val);
            }
            if (node.left != null) tq.add(node.left);
            if (node.right != null) tq.add(node.right);
            node.left = node.right = null;
        }
    }
    
    public int insert(int v) {
        TreeNode node = q.peek();
        TreeNode n = new TreeNode(v);
        if (node.left == null) {
            node.left = n;
        }
        else {
            node.right = n;
            q.poll();
        }
        q.add(n);
        return node.val;
    }
    
    public TreeNode get_root() {
        return this.root;
    }
}
posted on 2019-04-08 21:36  王 帅  阅读(132)  评论(0编辑  收藏  举报