Trees - 401-advanced-javascript-v/seattle-javascript-401d29 GitHub Wiki

Trees

There are two different types of trees that this tutorial will review:

Binary Trees

Binary Search Trees

Common Terminology

  • Node - a node is the individual item/data that make up the data structure.
  • Root - The root is the first/top Node in a tree
  • Left Child - The node that is positioned to the left of the root
  • Right Child - The node that is positioned to the right of the root
  • Edge - The edge in a tree is the link between two nodes
  • Leaf - A leaf is the node that does not contain either a left child or a right child node.
  • Height - The height of a tree is determined by the number of edges from the root to the bottommost node.

Traversals

There are two categories of traversals when it comes to trees.

Depth First

The biggest difference between each of the traversals is when you are looking at the root node.

  • Preorder PreOrder means that the root has to be looked at first. Root, Left, Right

  • Inorder Left, Root, Right

  • Postorder Left, Right, Root

Breadth First

Binary Trees

Binary Trees are trees that only contain no more than 2 children. There is not a specific sorting order for a binary tree. Nodes can be added into a binary tree wherever space allows.

Big O

The Big O time of an insertion an searching in a Binary tree will always be O(n). The Big O space for a node insertion using breadth first will be an O(w), with “w” being largest width of the tree.

Searching a BST

Here is an example: Let’s say we are searching for the node that contains 60.

  • First thing we do is compare 60 against the root. We can see that 60 is less than 100, so we will go left. We then compare 60 against the next root, 50. We know that 60 is greater than 50, so we will go right.
  • Next, we compare 60 against 75. We know that 75 is greater than 60, so we go left.
  • Finally, we compare 60 against 60. These numbers are exactly the same which tells us we found our node. We then return our node back to the user.

The best way to approach a BST search is with a while loop. The condition within this while loop would be to keep running until it hits a leaf.

Big O

The Big O of a Binary Search Tree for insertion and search is O(log n).