6.3Binary Tree with Linked Nodes
Insert: into the next free place
In an array tree the next free place was always index count. With linked nodes there is no such index; to find the first free place you have to walk the tree level by level. In this lesson you look for the first missing child with a queue and link the new node there. The tree grows in exactly the same shape as the array version.
- Why "the next free place" is the first missing child in level order
- What the queue does in this search
- Why the new node is returned as the root when the tree is empty
1Idea
This insertion keeps the tree complete: the new node goes into the first free place on the highest level that has one, from left to right. Adding 10, 20, 30, 40, 50, 60 in that order gives the sample tree. The value does not affect where it goes; the tree that places values by size is the binary search tree.
To find the first free place the nodes are visited in level order, and that takes a queue. The root goes into the queue. On each turn the front node is taken out and its children are checked: if left is NULL, the new node is linked there and the search ends. Otherwise the left child goes to the back of the queue and the same question is asked about right. The queue makes sure the nodes on one level are asked before the ones below.
If the tree is empty, that is if root is NULL, the new node is the whole tree. That is why the function always returns the root and the caller writes root = insert(root, 5). The root changes only in this case. In the C version the queue is a 100-element array inside the function; bigger trees need the queue built with a linked list.
The loop always ends with break: in a finite tree the bottom level is sure to have a missing child.
2Step by step
The drawing adds 60 to a tree holding 10, 20, 30, 40 and 50. The contents of the queue are shown under the drawing, with the front on the left. n is the node taken out of the queue.
- Start. The tree has five nodes; the next free place is the left child of 30. The code does not know that yet.
- A new node is allocated with value 60 and NULL children. It is not linked to the tree yet.
- The tree is not empty. The root goes into the queue: the queue holds only 10.
- The front, 10, is taken out and
npoints to it. The queue is empty for now. - The
leftof 10 is not NULL, 20 is there. The search goes on; 20 goes to the back of the queue. - The
rightof 10 is taken too, by 30. 30 joins the queue. Queue: 20, 30. - The front, 20, is taken out. 10 is done with and shown faded.
- Both children of 20 are there: 40 and 50 join the queue in that order. Queue: 30, 40, 50.
- The front, 30, is taken out. Queue: 40, 50.
- The
leftof 30 is NULL: the first free place is found.n->left = nodelinks 60, andbreakleaves the loop. - The function returns the unchanged root. 60 is now the left child of 30; the tree is still complete.
struct TreeNode { int data; struct TreeNode* left; struct TreeNode* right;}; struct TreeNode* newNode(int value) { struct TreeNode* n = malloc(sizeof(struct TreeNode)); if (n != NULL) { n->data = value; n->left = NULL; n->right = NULL; } return n;} struct TreeNode* insert(struct TreeNode* root, int value) { struct TreeNode* node = newNode(value); if (node == NULL) return root; // out of memory if (root == NULL) return node; // empty tree: the new node is the root struct TreeNode* queue[100]; int front = 0, rear = 0; queue[rear++] = root; while (front < rear) { struct TreeNode* n = queue[front++]; // take the front one if (n->left == NULL) { n->left = node; break; } queue[rear++] = n->left; if (n->right == NULL) { n->right = node; break; } queue[rear++] = n->right; } return root;}class TreeNode { int data; TreeNode left, right; TreeNode(int data) { this.data = data; }} TreeNode insert(TreeNode root, int value) { TreeNode node = new TreeNode(value); if (root == null) return node; // empty tree: the new node is the root java.util.ArrayDeque<TreeNode> queue = new java.util.ArrayDeque<>(); queue.add(root); while (!queue.isEmpty()) { TreeNode n = queue.poll(); // take the front one if (n.left == null) { n.left = node; break; } queue.add(n.left); if (n.right == null) { n.right = node; break; } queue.add(n.right); } return root;}from collections import deque class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def insert(root, value): node = TreeNode(value) if root is None: # empty tree: the new node is the root return node queue = deque([root]) while queue: n = queue.popleft() # take the front one if n.left is None: n.left = node break queue.append(n.left) if n.right is None: n.right = node break queue.append(n.right) return rootThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
In the worst case the first free place is on the bottom level and every node before it passes through the queue.
The queue can hold a whole level at once, which goes up to n/2 nodes.
In the array version the same insertion takes O(1), because the next place is index count. Linked nodes do not know the node count or where the last node is, so they have to search.
4Common mistake
A common mistake is looking for the free place by going left instead of using a queue:
struct TreeNode* n = root;while (n->left != NULL) n = n->left; // always go leftn->left = node;This code always adds the new node at the tip of the leftmost branch. After 10, 20, 30, the 30 goes under 20 and the tree turns into a list; the right side of the root never fills. Without a level-order search the tree does not stay complete. Another mistake is skipping the empty-tree case and going on with queue[rear++] = root while root is NULL: the loop then tries to read the fields of a NULL node.
5Try it
If 70 is also added to the sample tree (10, 20, 30, 40, 50, 60), where does it go?
The answer is B. In level order the first missing child is the right of 30. Level 2 is full only once that place is filled; then level 3 starts.
Show the answer
The answer is B. In level order the first missing child is the right of 30. Level 2 is full only once that place is filled; then level 3 starts.
What happens if this insertion uses a stack instead of a queue?
The answer is B. A queue asks the nodes on one level before those below. A stack gives the most recent node first, so the search dives deep into one branch and the tree does not stay complete.
Show the answer
The answer is B. A queue asks the nodes on one level before those below. A stack gives the most recent node first, so the search dives deep into one branch and the tree does not stay complete.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.