Insert: adding a new key
After this: Say where a new key goes and why it always starts as a leaf.
On this page · 7 sections · 3 checks
You can now search a tree. How do you add a new key? It has to go in a place where the order rule still holds, so that a later search can find it.
The answer uses what you already know: search for the key. The place where the search finds nothing is the place where the key belongs.
A small example
Take the tree of three keys and add 20.
- Compare 20 with 50. 20 is smaller, so go left.
- Compare 20 with 30. 20 is smaller, so go left.
- 30 has no left child. A search would stop here and say "not found". An insert puts the new node here instead, as the left child of 30.
Why is this the right place? A later search for 20 makes the same comparisons and the same turns, so it arrives at this exact spot and finds 20.
The same steps in the example tree
Where does 45 go in the example tree?
- Compare 45 with 50. 45 is smaller, so go left, to 30.
- Compare 45 with 30. 45 is larger, so go right, to 40.
- Compare 45 with 40. 45 is larger, so go right. Nothing is there, so attach 45 here, as the right child of 40.
That took three comparisons, one new node, and no change to any other node.
Here is the general rule. To insert a key, follow its search path. When the next step reaches an empty spot, attach the new node there. So a new key always starts as a leaf, and no existing node moves.
How the example tree was built
The example tree comes from inserting seven keys in the order 50, 30, 70, 20, 40, 60, 80 into an empty tree.
- 50: the tree is empty, so 50 becomes the root.
- 30: left of 50.
- 70: right of 50.
- 20: left at 50, then left at 30.
- 40: left at 50, then right at 30.
- 60: right at 50, then left at 70.
- 80: right at 50, then right at 70.
The result has height 2. A different order of the same keys can give a different shape. Why the shape matters shows how much this can change.
The code
This method belongs to the same BST class as search.
def insert(self, key): if self.root is None: self.root = Node(key) return node = self.root while True: if key == node.key: return # already here: no duplicates if key < node.key: if node.left is None: node.left = Node(key) # the path ended: it belongs here return node = node.left else: if node.right is None: node.right = Node(key) return node = node.right void insert(int key) { if (root == null) { root = new Node(key); return; } Node node = root; while (true) { if (key == node.key) return; // already here: no duplicates if (key < node.key) { if (node.left == null) { node.left = new Node(key); // the path ended: it belongs here return; } node = node.left; } else { if (node.right == null) { node.right = new Node(key); return; } node = node.right; } } }Here is how to read it.
- If the tree is empty, the new key becomes the root, and the method stops.
- Otherwise the loop moves down from the root, as a search does.
- If the key equals the node's key, it is already in the tree. The method stops and changes nothing, because this tree keeps no duplicates.
- If the key is smaller, the method looks at the left side. If there is no left child, it attaches the new node there and stops. If there is one, it moves to it.
- If the key is larger, it does the same on the right side.
The next block prints the path to 45 before and after inserting it.
t = BST()for k in [50, 30, 70, 20, 40, 60, 80]: t.insert(k)print(t.path(45)) # the path to a key that is not theret.insert(45)print(t.path(45)) # the same path, one node longer[50, 30, 40] [50, 30, 40, 45]
BST t = new BST();for (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) t.insert(k);System.out.println(t.path(45)); // the path to a key that is not theret.insert(45);System.out.println(t.path(45)); // the same path, one node longer[50, 30, 40] [50, 30, 40, 45]
The second path is the first path with 45 on the end. The insert put the key exactly where the failed search had stopped.
Watch it happen
Before the second insert runs, the task asks for a prediction. Tap the node you think 65 will attach to. Then watch the path confirm or correct your choice.
- Search for 45Search for 45 first. The path ends at 40, and there is nothing on its right.
- Insert 45
- Insert 65
- Insert 10
Run an operation to begin.
Each insert costs one comparison per level, as a search does, and ends by attaching a leaf.
Check yourself
Insert 35 into the example tree (root 50; then 30 and 70; then 20, 40, 60 and 80). Where does it go?
What does this print?
t = BST()for k in [50, 30, 70, 20, 40, 60, 80]: t.insert(k)print(t.path(45)) # the path to a key that is not theret.insert(45)print(t.path(45)) # the same path, one node longerBST t = new BST();for (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) t.insert(k);System.out.println(t.path(45)); // the path to a key that is not theret.insert(45);System.out.println(t.path(45)); // the same path, one node longerStart from an empty tree. Insert 40, 20, 60, 10, 30, in that order. Which tree do you get?
Connect
- Insert a key by searching until the path ends, then attaching the key there as a leaf.
- Say where a given key goes in a given tree, by naming its parent and its side.
- Build the example tree from its insertion order, and explain why no existing node moves.