0

Right now I'm trying to write a binary heap in Java implemented over a binary tree structure, and while I do have a very good grasp on how to "heapify" the tree after adding an element, the logic for finding the first unoccupied leaf at the bottom of the heap eludes me.

I'm aware that finding the first unoccupied leaf is supposed to be a breadth-first traversal, but I still can't figure out how exactly a breadth-first traversal algorithm would work.

user2309750
  • 1,403
  • 4
  • 14
  • 11

1 Answers1

0

This is what a breadth-first search for the first null branch (followed by an insertion to the branch) would look like. Note that this is basically the same as a depth-first insert, except that this uses a queue where a depth-first insert uses a stack.

void breadthFirstInsert(Node root, Object obj) {
    Queue<Node> queue = new LinkedList<>();
    queue.offer(root);
    while(!queue.isEmpty()) {
        Node temp = queue.poll();
        if(temp.left != null) {
            queue.offer(temp.left);
        } else {
            temp.left = new Node(obj);
            return;
        }
        if(temp.right != null) {
            queue.offer(temp.right);
        } else {
            temp.right = new Node(obj);
            return;
        }
    }
}
Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
  • Thank you! I'm a bit confused about something, though. Since you're only adding the new node to a temporary variable, does that mean it wouldn't be added to the original tree? – user2309750 Apr 25 '13 at 14:47
  • It will be added to the original tree, because temp is a copy of a reference pointing to a tree node. For example, `Node temp = root; temp.left = new Node(obj)` is equivalent to `root.left = new Node(obj)`; `Node temp = root; temp = temp.left; temp.right = new Node(obj)` is equivalent to `root.left.right = new Node(obj)` – Zim-Zam O'Pootertoot Apr 25 '13 at 14:52