home/ docs/ cv.txt photos/2030354050607080<html> <head> <body> <p>10203040[0][1][2][3][4][5][6][7]
Nodes: one value each, linked to at most two childrenToken: the value being searched for or insertedOutput row: the in-order traversal, left to rightCards: folders and an HTML page, trees you already useThe tree stands on a board with its root at the top. Each node stands in the column of its sorted position, so reading the nodes left to right, or dropping them into the row in front, gives the values in order. To search, a token starts at the root and at each node goes left if it is smaller and right if it is larger, so it only visits one node per level. Inserting walks the same way and adds a new leaf where the walk runs out. O(log n), read "order log n", means the work grows like the logarithm of n: doubling the number of values adds about one more comparison. O(n) means the work grows in step with n.

What a tree is

  1. A tree stores values in nodes. Each node can link down to child nodes. Here every node holds a number and has at most two children, a left one and a right one. A tree like that is a binary tree.

Binary search trees

Insert and shape

Traversal

Try it in the Python prompt

;; step 1/10 · Nodes and children
>>> class Node:
...     def __init__(self, key):
...         self.key = key
...         self.left = None     # left child
...         self.right = None    # right child
...
>>> top = Node(50)
>>> top.left = Node(30)
>>> top.right = Node(70)
>>> top.left.key
30

O(log n), read "order log n", means the work grows like the logarithm of n: doubling the number of values adds about one more comparison. O(n) means the work grows in step with n. A plain binary search tree only stays balanced if the values arrive in a mixed-up order. Self-balancing trees, such as red-black trees and AVL trees, reshape themselves on every insert so the height stays about log2(n).