reading-notes

Trees

A tree data structure consists of:

Tree visual structure

trees

Pseudocode for this traversal of a tree method

ALGORITHM preOrder(root)

OUTPUT <-- root.value

if root.left is not NULL

  preOrder(root.left)

if root.right is not NULL

  preOrder(root.right)

Binary trees

A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child.

bt

A Binary Tree node contains following parts.

Implementation

class Node:

def __init__(self, data):
    # left child
    self.left = None
    # right child
    self.right = None
    # node's value
    self.data = data

K-ary Trees

Traversing a K-ary tree requires a similar approach to the breadth first traversal.

kt

If we traversed this tree Breadth First we should see the output:

Output: A, B, C, D, E, F, G, H

enqueue

dequeue

Pseudocode

ALGORITHM breadthFirst(root)

// INPUT <-- root node

// OUTPUT <-- front node of queue to console

Queue breadth <-- new Queue()

breadth.enqueue(root)

while breadth.peek()

node front = breadth.dequeue()
OUTPUT <-- front.value

for child in front.children
    breadth.enqueue(child)

Summary

Types of trees:

Tree operations:

Trees applications: