m22 Flashcards

1
Q

BST structure, recursive definition

A

```java
public class Node {
int key;
Node left, right;

public Node(int item) {
    key = item;
    left = right = null;
} } ~~~
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Recursive Insert

A

public Node insert(Node node, int key) {
if (node == null) {
return new Node(key);
}
if (key < node.key) {
node.left = insert(node.left, key);
} else if (key > node.key) {
node.right = insert(node.right, key);
}
return node;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Recursive search

A

public boolean search(Node root, int key) {
if (root == null) {
return false;
}
if (root.key == key) {
return true;
}
return key < root.key ? search(root.left, key) : search(root.right, key);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Generic BST class

A

public class BST {
private Node root;

private static class Node {
    int root;
    Node left, right;

    public Node(int root) {
        this.root = root;
        left = right = null;
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Inorder traversal of BST

A

void inorder() {
inorder(root);
}

void inorder(Node root) {
if (root != null) {
inorder(root.left);
System.out.println(root.key);
inorder(root.right);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Algorithm + code for BST delete

A

void deleteKey(int key) {
root = deleteRec(root, key);
}

Node deleteRec(Node root, int key) {
    if (root == null)  return root;

    if (key < root.key)
        root.left = deleteRec(root.left, key);
    else if (key > root.key)
        root.right = deleteRec(root.right, key);

    else {
        if (root.left == null)
            return root.right;
        else if (root.right == null)
            return root.left;

        root.key = minValue(root.right);
        root.right = deleteRec(root.right, root.key);
    }

    return root;
}  int minValue(Node root) {
    int minv = root.key;
    while (root.left != null) {
        minv = root.left.key;
        root = root.left;
    }
    return minv;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What to do when keys are not unique? (maintain, at every node, a list of all objects with same key)

A

If keys are not unique, you can store a list of objects at each node.
This will mean changing the structure of your node to hold a list instead of a single value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Big O worst case analysis for search, insert, delete

A

The worst case for these operations in a binary search tree is O(n),
where n is the number of nodes in the tree.
This would occur in the case where the tree is a straight line (each node only has a right child or only
has a left child).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

traversals: inorder, preorder, postorder

A

void inorder(Node root) {
if (root != null) {
inorder(root.left);
System.out.println(root.key);
inorder(root.right);
}
}

void preorder(Node root) {
if (root != null) {
System.out.println(root.key);
preorder(root.left);
preorder(root.right);
}
}

void postorder(Node root) {
if (root != null) {
postorder(root.left);
postorder(root.right);
System.out.println(root.key);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is a balanced tree?

A

A balanced tree is a tree structure in which the left and right subtrees of any node differ in height by
no more than one. In other words, elements are evenly distributed across the tree.
Balanced trees are optimized to ensure that operations like search, insert, and delete take the least time
possible.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Red-Black Tree Properties

A

A Red-Black Tree is a self-balancing binary search tree, and it follows these properties:

  1. Every node is either red or black.
  2. The root node is always black.
  3. All leaves (NULL or NIL nodes) are black.
  4. If a node is red, then both its children are black (no two consecutive Red nodes).
  5. For each node, any simple path from this node to any of its descendant leaves has the same number
    of black nodes.

These properties ensure that the tree remains approximately balanced, resulting in O(log n) search times.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Rotations

A

Rotations are operations in balanced BSTs that help maintain their balance while performing insertions
and deletions. There are two types of rotations: left rotation and right rotation.

  • Left Rotation: Suppose node x is a node in the tree with a right child, y. A left rotation on x moves y up
    to x’s position, moves x down to y’s left child position, and moves y’s original left child to be x’s right child.
  • Right Rotation: It’s the reverse of the left rotation. Suppose y is a node in the tree with a left child x.
    A right rotation on y moves x up to y’s position, moves y down to x’s right child position,
    and moves x’s original right child to be y’s left child.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Time complexity of insert, delete, and search in a Red-Black Tree

A

The search operation in a Red-Black Tree behaves exactly as it does in a binary search tree,
and thus its time complexity is O(log n) in the worst-case scenario.

The insert and delete operations in a Red-Black Tree are more complicated because they may
require rebalancing of the tree and recoloring of the nodes.
Despite this, these operations can be done in O(log n) time in the worst case.
The reason is that the tree remains balanced, i.e., the height of the tree remains proportional to
the logarithm of the number of nodes, and the operations require time proportional to the height of the tree.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Expression tree evaluation: Expression trees can be evaluated using a postorder traversal.
You traverse the tree, when you encounter an operator, you apply it to the results of evaluating its
two subtrees. If you encounter a leaf node (an operand), you simply return its value.

A

public int evaluate(Node root) {
if (root == null) {
return 0;
}

if (root.left == null && root.right == null) {
    return toInt(root.value);
}

int leftSum = evaluate(root.left);
int rightSum = evaluate(root.right);

if (root.value.equals("+")) {
    return leftSum + rightSum;
}

if (root.value.equals("-")) {
    return leftSum - rightSum;
}

if (root.value.equals("*")) {
    return leftSum * rightSum;
}

return leftSum / rightSum;  // assuming the root.value is "/" }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Infix, prefix, postfix

A

These are all notations for writing arithmetic expressions that
eliminate the need for parentheses to indicate the order of operations.

  • Infix notation: Operators are written between the operands. Ex: 2 + 3.
  • Prefix notation (Polish notation): Operators are written before the operands. Ex: + 2 3.
  • Postfix notation (Reverse Polish notation): Operators are written after the operands. Ex: 2 3 +.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Computing the tree given infix and another traversal

A

If both an inorder traversal and either a preorder or postorder traversal are given,
the original tree can be reconstructed. This is because the inorder traversal gives the relative
ordering of values, and the preorder/postorder traversal gives the root of each subtree.

17
Q

Evaluation of a postfix expression using a stack

A

Postfix expressions can be evaluated
easily using a stack.

  1. Read the postfix expression from left to right.
  2. If the symbol is an operand, push it onto the stack.
  3. If the symbol is an operator, pop the top two values from the stack, apply the operator to the
    popped values, and push the result back on the stack.
  4. When the expression has been completely read, the result is on the top of the stack.

Here’s a Java code snippet that demonstrates this:

```java
public int evaluatePostfix(String expression) {
Stack<Integer> stack = new Stack<>();</Integer>

for (int i = 0; i < expression.length(); i++) {
    char c = expression.charAt(i);
    
    if (Character.isDigit(c)) {
        stack.push(c - '0');
    } else {
        int value1 = stack.pop();
        int value2 = stack.pop();
        
        switch (c) {
            case '+':
                stack.push(value2 + value1);
                break;
                
            case '-':
                stack.push(value2 - value1);
                break;

case ‘*’:
stack.push(value2 * value1);
break;

            case '/':
                stack.push(value2 / value1);
                break;
        }
    }
}
return stack.pop(); } ~~~
18
Q

Heap property (min and max)

A

A heap is a complete binary tree that satisfies the heap property.
If each parent node is less than or equal to its child node then the property is called min heap property.
If each parent node is greater than or equal to its child node then it is called max heap property.
So a heap is called a min heap or max heap.

19
Q

Heap structure and ordering

A

A heap is a binary tree that is completely filled, with the possible
exception of the bottom level, which is filled from left to right.
In a max heap, each node’s value is greater than or equal to the values of its children.
In a min heap, each node’s value is less than or equal to the values of its children.

20
Q

Heap methods

A

Basic operations of a heap include:

  • insert: Inserts a new element into the heap, maintaining the heap property.
  • extractMax or extractMin: Removes and returns the maximum element (for a max heap)
    or the minimum element (for a min heap) from the heap.
  • peek: Returns the maximum (for a max heap) or minimum (for a min heap) from the heap
    without removing it.
  • delete: Removes a specific item from the heap, maintaining the heap property.
21
Q

Heap insert and bubble up - algorithm

A

The process to insert a new element into a heap and
then adjust it to maintain the heap property is known as “bubble up” or “up-heap” operation.
The new element is initially appended to the end of the heap (as the last node of the complete binary tree).
The heap property is repaired by comparing the added element with its parent and moving the added
element up a level (swapping positions with the parent node). The action is repeated until the heap
property is restored.

22
Q

Heap delete and sift down - algorithm

A

Deletion in a heap is performed by removing the root
and replacing it with the last node in the last level. The heap property is repaired by comparing the
new root node with its children and moving it down a level (i.e., swapping positions with the appropriate
child). This process is known as “sift down” or “down-heap” operation. The action is repeated until the
heap property is restored.

23
Q

Worst case number of comparisons (bubble up and sift down)

A

In the worst-case scenario,
bubble up and sift down operations can make a number of comparisons equal to the height of the tree.
For a binary heap with n elements, the height of the tree is log(n), so the worst-case number of
comparisons is O(log n).

24
Q

Insert and extract running time analysis big O

A

Both insert and extract operations involve
a “bubble up” or “sift down” process that, in the worst case, involves moving an element from
the root of the tree to the bottom or vice versa. Thus, both operations have a time complexity of
O(log n) where n is the number of elements in the heap.