LAB 11

Topic: Trees

Tasks

Task 0

Implement tree structure

class TNode{
    int key;
    TNode left;
    TNode right;
}

class Tree{
    TNode root;

    ....


}

Task 1

Compute number of nodes in a tree

int noOfNode();


recursive idea:
    #leftSubTree+#rightSubTree+1

Task 2

Find maximal key

int noOfNode();


recursive idea:
    max{leftSubTree,rightSubTree,key}

Types of trees

Traversals of trees


Implementations of Tree Traversals

Alg

    x-order(node)

     if node == null then return
        (a) print(node)            
        (b) x-order(node.left) 
        (c) x-order(node.right)

Alg

Class Qnode{
    Qnode next
    int   val
}

Class Queue{
    QNode head 
          tial

Boolean empty()

void enqueue(int value)

    Qnode  qn  = new Qnode(value,null)

    if empty
        head = tail = qn
    else
        tail.next = qn
        tail = qn


int dqueue()
    // take the last element in the list
}

Alg

    levelorder(root)
      q = empty queue
      q.enqueue(root)
      while not q.empty do
        node := q.dequeue()
        visit(node)
        if node.left ≠ null then
          q.enqueue(node.left)
        if node.right ≠ null then
          q.enqueue(node.right)

Serialization problem

Q: How to store BST such that after we read the elements of the tree using sequentially we again get the same tree?

We want a serialization method such that

Tree = array2BST ( serialize (Tree))