Trees in C
In questa pagina 5
Theory of binary trees, traversals and balancing in the sibling subject: Binary TreesA binary tree is an ordered tree where each node has at most two children (left and right); in a proper binary tree every internal node has exactly two, which gives the leaf count m = n - m + 1 and bounds linking height, leaves and nodes.Binary Trees →, Tree TraversalsPreorder visits a node before its subtrees (top-down), postorder after them (bottom-up); both run in time proportional to the number of nodes plus the cost of the visits, and are design patterns for algorithms on trees.Tree Traversals →, HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps →; recursion in Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →. Lists: Linked Lists in CA linked list is a chain of dynamically allocated nodes, each holding data and a pointer to the next one; insertion and deletion only relink pointers, but access is sequential.Linked Lists in C →.
Definitions
A tree is a set of nodes with a "descent" relationship and two properties:
- a single node, the root, has no predecessor;
- every other node has a unique predecessor.
Nodes with no successors are leaves; nodes that are neither root nor leaf are intermediate. The tree is divided into levels.
Slide example: t is the root; v is an intermediate node; u, x, y, z are leaves. The tree has three levels (L0, L1, L2), so its depth is 2; node v has the maximum output degree (3).
| Term | Meaning |
|---|---|
| Exit (output) degree of a node | number of direct successors |
| Depth of a node | distance from the root (root has depth 0) |
| Depth of the tree | maximum depth of its nodes |
| Level | set of nodes at the same depth |
| Balanced tree | at every node the depth of the subtrees differs by at most 1 |
About balance (slides): balanced trees guarantee O(log n) search, insertion, deletion; AVL and Red-Black trees use rotations to restore balance; used in databases, compilers, file systems.
Compared with a list: a tree has several leaves, not one terminal node; an insertion must be qualified with a criterion that selects the target leaf; inserting at the head or in an intermediate position tends to degenerate the tree into a sequence, so insertions are typically made on leaves.
Binary trees
A binary tree: each node has at most 2 children, called left and right. A tree is represented by a pointer to the root; empty tree = NULL root. Each node holds: data, pointer to left child, pointer to right child.
// Structure of each node of the tree
struct node {
int data;
struct node* left_child;
struct node* right_child;
};Operations: basic (insert, remove, search, traverse); auxiliary (height of the tree, level of a node, size of the tree).
Binary search tree (BST)
A binary tree that stores elements in sorted manner and can be searched in O(log n) time (for a balanced one). Properties:
- all nodes in the left subtree have a value less than the node;
- all nodes in the right subtree have a value greater than the node;
- both subtrees are themselves BSTs.
Slide figure: a tree is not a BST when, e.g., the right subtree of node 3 contains a smaller value.
Creating a node
/* newNode() allocates a new node with the given data and NULL left and right pointers. */
struct node* newNode(int data)
{
// Allocate memory for new node
struct node* node = (struct node*)malloc(sizeof(struct node));
if (node != NULL) {
// Assign data to this node
node->data = data;
// Initialize left and right children as NULL
node->left_child = NULL;
node->right_child = NULL;
}
return(node);
}Search
Compare with the root: equal -> return it; smaller -> go to the left subtree; larger -> right subtree; not found -> NULL. Slide example: search 20, following one branch at each step.
// searching operation
struct node* search(struct node * root, int x) {
if (root == NULL || root->data == x) //if root->data is x then the element is found
return(root);
else if (x > root->data) // x is greater, so we search the right subtree
return(search(root->right_child, x));
else //x is smaller than the data, so we search the left subtree
return(search(root->left_child, x));
}Insertion
Always done at a leaf: search from the root for the empty location (left if smaller, right otherwise). Slide example: insert 65.
// insertion
struct node* insert(struct node * root, int x) {
//searching for the place to insert
if (root == NULL)
return newNode(x);
else if (x > root->data) // x is greater. Should be inserted to the right
root->right_child = insert(root->right_child, x);
else // x is smaller and should be inserted to left
root->left_child = insert(root->left_child, x);
return(root);
}The function returns the (possibly new) root of the subtree and the caller re-links it (root->right_child = insert(...)), so no ** is needed. Equal values go to the left (the else branch).
Deletion
Must keep the BST properties. Three cases:
- Leaf: replace with
NULLand free it (slide example: delete 90). - One child: replace the node with its child (slide example: delete 79, replaced by its child 55).
- Two children: find the inorder successor (minimum of the right subtree), put its value in the node, then delete the successor from the right subtree (slide example: delete the root 45, replaced by its in-order successor 55; the old position then ends up at a leaf and is deleted easily).
// deletion
struct node* delete(struct node * root, int x) {
//searching for the item to be deleted
if (root == NULL)
return(NULL);
if (x >root->data)
root->right_child = delete(root->right_child, x);
else if (x < root->data)
root->left_child = delete(root->left_child, x);
else {
//No Child node
if (root->left_child == NULL && root->right_child == NULL) {
free(root);
return(NULL);
}
//One Child node
else if (root->left_child == NULL || root->right_child == NULL) {
struct node *tmp;
if (root->left_child == NULL)
tmp = root->right_child;
else
tmp = root->left_child;
free(root);
return(tmp);
}
//Two Children
else {
struct node *tmp = find_minimum(root->right_child);
root->data = tmp->data;
root->right_child = delete(root->right_child, tmp->data);
}
}
return(root);
}Inorder successor = minimum of a subtree = the left-most node (it has no left child):
//function to find the minimum value in a node
struct node* find_minimum(struct node * root) {
if (root == NULL)
return(NULL);
else if (root->left_child != NULL)
// node with minimum value will have no left child
return find_minimum(root->left_child);
// left most element will be minimum
return(root);
}Traversals
// Inorder Traversal (Left -> Root -> Right)
void inorder(struct node *root) {
if (root != NULL) // checking if the root is not null
{
inorder(root->left_child); // traversing left child
printf(" %d ", root->data); // printing data at root
inorder(root->right_child); // traversing right child
}
}
// Preorder Traversal (Root -> Left -> Right)
void preorder(struct node *root) {
if (root != NULL)
{
printf(" %d ", root->data);
preorder(root->left_child);
preorder(root->right_child);
}
}
// Postorder Traversal (Left -> Right -> Root)
void postorder(struct node *root) {
if (root != NULL)
{
postorder(root->left_child);
postorder(root->right_child);
printf(" %d ", root->data);
}
}| Traversal | Order | Note |
|---|---|---|
| inorder | left, root, right | visits a BST in ascending order |
| preorder | root, left, right | |
| postorder | left, right, root | children before the parent |
| level order | level by level, using a queue | see below |
Level order uses a queue (Stacks and Queues in CA stack is LIFO (push/pop at the top), a queue is FIFO (enqueue at the rear, dequeue at the front); both can be built on an array or on a linked list, all operations in constant time.Stacks and Queues in C →): enqueue the root; while the queue is not empty, dequeue a node, print it, enqueue its left and right children if present.
// Level order Traversal
void levelOrder(struct Node* root) {
if (root == NULL) return;
struct Queue* q = createQueue();
enqueue(q, root);
while (!isEmpty(q)) {
struct Node* current = dequeue(q);
printf("%d ", current->data);
if (current->left) enqueue(q, current->left);
if (current->right) enqueue(q, current->right);
}
}The slide's comment says "(Left -> Right -> Root)", which is the postorder rule, not level order. The code also uses struct Node with fields left/right and a queue of node pointers, while the tree above is struct node with left_child/right_child and the queue of the previous deck stores int: the queue must be adapted to hold node pointers.
Exercises (slides)
1. Search sequences. Numbers 1 to 1000 are in a BST and we search for 825. Which sequence of examined nodes is possible?
- A) 923, 510, 655, 715, 798, 822, 901, 820, 825
- B) 41, 405, 889, 488, 626, 674, 821, 858, 857, 823, 825
- C) 599, 974, 754, 947, 889, 764, 851, 748, 848, 832, 825
- D) 991, 63, 535, 901, 670, 804, 817, 905, 831, 825
- E) 500, 793, 884, 856, 837, 792, 806, 825
The slides give no answer. Working it out with the BST property (every node on the path narrows an interval for the following keys): going toward 825, each next node must lie strictly between the last "went right" node and the last "went left" node. A fails at 820 (after 822 we went right, so later keys must be greater than 822), C fails at 748 (after 764), D fails at 905 (after 901 we went left, so later keys must be smaller than 901), E fails at 792 (after 793 we went right). Only B is possible.
2. Find minimum and maximum. Write findMin(Node* root) (smallest value) and findMax(Node* root) (largest value). Create a BST inserting, in this order: 50, 37, 70, 22, 40, 68, 80, 13, 118, 97.
find_minimum above goes left until there is no left child; findMax is its mirror (go right). Working it out for the given insertion order: 50 is the root; 37 and 70 are its children; 22 and 40 hang under 37; 68 and 80 under 70; 13 under 22; 118 under 80; 97 under 118. Minimum 13, maximum 118. Inorder: 13 22 37 40 50 68 70 80 97 118; preorder: 50 37 22 13 40 70 68 80 118 97; postorder: 13 22 40 37 68 97 118 80 70 50; height 4 (path 50, 70, 80, 118, 97).
More tree exercises (airports BST, deleting leaves): Lab Exercises - Lists, Arrays and TreesLab problem sets on linked lists, stacks, queues, arrays and binary search trees, with the statements, the data declarations and program skeletons given on the slides, plus the quiz questions.Lab Exercises - Lists, Arrays and Trees →.
Versione ripasso
- Tree: one root without predecessor, every other node has a unique predecessor. Leaves have no successors; the root has depth 0; the depth of the tree is the maximum node depth. A tree is balanced when at every node the subtree depths differ by at most 1: then search, insert and delete are O(log n); AVL and Red-Black trees restore balance with rotations. See Binary TreesA binary tree is an ordered tree where each node has at most two children (left and right); in a proper binary tree every internal node has exactly two, which gives the leaf count m = n - m + 1 and bounds linking height, leaves and nodes.Binary Trees →.
- Insert on leaves: an insertion in the middle or at the head tends to turn the tree into a sequence, so new nodes go to a leaf chosen by a criterion.
- Node:
struct node { int data; struct node* left_child; struct node* right_child; };, empty tree =NULLroot.newNode(data)allocates the node and sets both children toNULL, checking themallocresult. - BST: all values of the left subtree are less than the node, all values of the right subtree are greater, and both subtrees are BSTs themselves. Search, insert and delete follow one path.
search(root, x):NULLor equal -> return root;x > data-> recurse right; else recurse left.insert(root, x):NULL->newNode(x); else recurse left (if smaller) or right and reassignroot->child = insert(...); returnroot. Equal values go left.delete(root, x)has three cases: leaf ->free, returnNULL; one child ->free, return the child; two children -> copy the inorder successor (minimum of the right subtree, found withfind_minimumby going left until there is no left child) into the node, then delete that value from the right subtree. Example from the slides: deleting the root 45 puts 55 there.- Traversals (Tree TraversalsPreorder visits a node before its subtrees (top-down), postorder after them (bottom-up); both run in time proportional to the number of nodes plus the cost of the visits, and are design patterns for algorithms on trees.Tree Traversals →): inorder left, root, right (sorted for a BST); preorder root, left, right; postorder left, right, root (children before parent); level order, one level at a time with a queue (Stacks and Queues in CA stack is LIFO (push/pop at the top), a queue is FIFO (enqueue at the rear, dequeue at the front); both can be built on an array or on a linked list, all operations in constant time.Stacks and Queues in C →): enqueue the root, then while the queue is not empty dequeue a node, print it and enqueue its children.
- Search sequence test (exercise 825): every examined node must lie inside the interval fixed by the earlier left and right turns. Options A, C, D and E each break this rule (A at 820, C at 748, D at 905, E at 792), so only B is possible.
- BST built by inserting
50, 37, 70, 22, 40, 68, 80, 13, 118, 97in this order: min 13, max 118, height 4 (path 50, 70, 80, 118, 97). Inorder13 22 37 40 50 68 70 80 97 118, preorder50 37 22 13 40 70 68 80 118 97, postorder13 22 40 37 68 97 118 80 70 50. findMaxis the mirror offind_minimum: go right until there is no right child.- Exercises with the airports BST and deleting leaves: Lab Exercises - Lists, Arrays and TreesLab problem sets on linked lists, stacks, queues, arrays and binary search trees, with the statements, the data declarations and program skeletons given on the slides, plus the quiz questions.Lab Exercises - Lists, Arrays and Trees →.
- Typical errors: not reassigning the child pointer after a recursive insert or delete; deleting a two-children node without moving the successor; the slides' level-order sample mixes
struct Nodewithleftandrightand thestruct nodeof the other sample (left_child,right_child), and its queue storesintwhere it must store node pointers.