CSC416 lecture note on Trees


[W: 4.1-4.2, 4.6] Trees, Binary Trees

1. Basic Concepts

2. Binary Trees

3. Mathematical Properties of binary trees

  1. Number of nodes on each level i is at most 2i

    Those are upper bound numbers which hold when a tree is fully expanded (i.e., a tree of depth d is complete and all nodes at depth 0 through d-1 have two children).

  2. Total number of nodes in a (general) binary tree of depth d is

  3. Depth of a binary tree with N nodes >= floor(lgN)

Exercises:

  1. How many nodes are in a fully expanded binary tree of depth 5? Of them, how many are internal, and how many are leaf nodes?



  2. What is the depth of a complete binary tree with 200 nodes?



4. Class BinaryNode

class BinaryNode
{
  // constructors
  BinaryNode( Comparable o ) { element = o; }
  BinaryNode( Comparable o, BinaryNode lt, BinaryNode rt )
  {
    element  = o;
    left     = lt;
    right    = rt;
  }
  // fields
  Comparable element;
  BinaryNode left;
  BinaryNode right;
}

5. Inorder/Preorder/Postorder Tree Traversals

             A
           /   \
          B     F
           \   / 
           C   G
          / \
         D   E

There are three different orders to visit nodes:

  1. Preorder -- 1) visit current node, 2) go left, then 3) go right
  2. Inorder -- 1) go left, 2) visit current node, then 3) go right
  3. Postorder -- 1) go left, 2) go right, then 3) visit current node
Preorder:  A B C D E F G
Inorder:   B D C E A G F
Postorder: D E C B G F A

6. Recursion and Binary Trees

7. Expression Tree

Preorder:  - * 3 5 2
Inorder:   3 * 5 - 2
Postorder: 3 5 * 2 -