Trees

Where do you see "trees"?

Binary Trees

Terminology:
  • nodes;
  • parent;
  • children;
  • edge;
  • path
Side note: why trees?

Because arrays and linked lists don't provide both fast...

Array
Linked List
Sorted Array
search
O(n)
O(n)
O(log n)
insert
O(1) (add to the end of the list)
O(1) (add to the end of the list)
O(n)
...and trees can provide both at O(log n)

Given a tree, the depth of a node M in the tree is the length of the path from the root of the tree to M. All nodes of depth d are at level d in the tree.

The height of a tree is one more than the depth of the deepest node in the tree.

A B C D E F Sorry, your browser does not support inline SVG.
Figure 1: A binary tree with 6 nodes.
Node A is the root, which has two children, B and C.
Nodes B and D together form a subtree.
The height of this tree is 3.
D, E and F make up level 2 of the tree (with depth of 2); they are leaves (leaf nodes that have no children, or two empty children).

Full vs Complete Binary Trees

How is the data stored in a tree?

Array Implementation for Complete Binary Trees

Complete binary trees have all levels except the bottom filled out completely, and the bottom level has all of its nodes filled in from left to right. So a complete binary tree with n nodes only has one shape. Complete binary trees (including heaps) can be implemented using arrays, as simple formulas can be used for computing the array index for each relative of a node $r$ from $r's$ index as follows.
0 1 2 3 4 5 6 7 8 9 10 11 Example: parent('4') = (4 - 1)/2 = 1 Sorry, your browser does not support inline SVG.

Binary Tree Traversals (Chapter 5.2)

Given a binary tree,

Binary Search Trees (BST)

Recursion

Heaps

Priority Queues

Huffman Coding Trees