LOGBOOK

HELP

1 / 73
time's up — finish this card
Other keys: show • Space: good • 1-4: rate • 0: skip • 5: flag
Topic Trees: Structure, Storage and Traversals

Question

Which methods does the BinaryTree ADT add to the Tree ADT?

Answer

It inherits every Tree ADT method and adds left(p), right(p) and sibling(p).

A binary tree is still a tree, so root, parent, children, isInternal, isExternal and the rest all remain available. The three additions exist because the left/right distinction is the defining feature of a binary tree:

  • left(p) — the left child of p (or nothing if it has none)
  • right(p) — the right child of p
  • sibling(p) — the other child of p's parent

children(p) alone would lose information here: it returns the children as a list, and a list with one element cannot say whether that element is the left or the right child.

sibling(p) is a convenience: it is the parent's other child, which algorithms often need (for example, when restructuring a tree after a deletion).

or press any other key
Topic Linear Data Structures: Lists, Stacks, Queues, Deques, Iterators

Question

How do you insert a node at the head of a singly-linked list, and why does the order of the steps matter?

Answer

First point the new node at the old head (v.next ← head), then move head to the new node (head ← v), then increment size — $O(1)$.

addFirst: new node v links to the old first node, then head moves to v

* Step ① keeps the old list reachable through v before step ② moves head away from it. *

Algorithm addFirst(v)
  v.setNext(head)     { new node points to the old first node }
  head ← v            { head now points to the new node }
  size ← size + 1

Why the order matters: head is the only reference to the existing chain. If you did head ← v first, the old first node would no longer be referenced by anything, and v.setNext(head) would then make v point to itself. The rest of the list would be lost. Linking the new node before moving the entry point is the general rule for pointer surgery: never overwrite a reference until something else holds on to what it pointed to.

The operation touches a constant number of references regardless of the list length, so it runs in $O(1)$. It also works on an empty list: head is null, so v.next becomes null and v is the only node.

or press any other key