View on GitHub

reads

https://yazansneneh.github.io/reads/

Implementation: Trees

Traversing tree (iterate)

  1. Depth First:
    • Depth first visit tree nodes from root to the down end of tree node by node.
    • It uses Stack.
    • There are 3 methods to iterate using depth:
      • pre order depth.
      • in order depth.
      • post order depth.
Pre Order
public void preOrder(root):

    if root.left not null 
            preOrder(root.left)
    
    print = root.value

    if root.right not null
            preorder(root.right)
public void preOrder(root):

    if root.left not null 
            preOrder(root.left)
    if root.right not null
            preorder(root.right)
    
     print = root.value
  1. Breadth First:
    • visit tree nodes From top level to last level from left to right then enqueue values.
    • so it first enqueue root, then next children level enqueue and so on.
    • it uses queue.
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

    if front.left is not NULL
      breadth.enqueue(front.left)

    if front.right is not NULL
      breadth.enqueue(front.right)

resource Code Fellows

Binary Tree Vs K-ary Trees

k-ary Tree

Adding a node

Big O

Binary Search Trees (BST)

#### Big O