The process of viewing each node in a binary tree in a specified order is referred to as binary tree traversal. There are three popular traversal techniques:
Pseudo-code:
void Inorder(struct node* ptr)
{
if(ptr != NULL)
{
Inorder(ptr->left);
printf("%d", ptr->data);
Inorder(ptr->right);
}
}
Pseudo-code:
void Preorder(struct node* ptr)
{
if(ptr != NULL)
{
printf("%d", ptr->data);
Preorder(ptr->left);
Preorder(ptr->right);
}
}
Pseudo-code:
void Postorder(struct node* ptr)
{
if(ptr != NULL)
{
Postorder(ptr->left);
Postorder(ptr->right);
printf(“%d”, ptr->data);
}
}
In addition to the above three basic traversals, there are two more specialized traversals:
Pseudo-code:
void levelOrderTraversal(struct Node* root) {
// Check if the tree is empty
if (root == NULL)
return;
// Create a queue for level-order traversal
struct Node** queue = (struct Node**)malloc(sizeof(struct Node*));
int front = 0;
int rear = 0;
// Enqueue the root node
queue[rear] = root;
rear++;
while (front < rear) {
// Dequeue a node from the queue
struct Node* current = queue[front];
front++;
// Process the current node
printf("%d ", current->data);
// Enqueue the left child if it exists
if (current->left != NULL) {
queue = (struct Node**)realloc(queue, (rear + 1) * sizeof(struct Node*));
queue[rear] = current->left;
rear++;
}
// Enqueue the right child if it exists
if (current->right != NULL) {
queue = (struct Node**)realloc(queue, (rear + 1) * sizeof(struct Node*));
queue[rear] = current->right;
rear++;
}
}
// Free the memory allocated for the queue
free(queue);
}
Traversal Algorithm | Time Complexity | Space Complexity |
---|---|---|
Preorder | O(n) | O(h) |
Inorder | O(n) | O(h) |
Postorder | O(n) | O(h) |
Level-order | O(n) | O(w) |
Note:
In the worst case, the space complexity for all traversals can be O(n) for a skewed tree, where the height of the tree is equal to the number of nodes.
Note: also read about Queues in DSA
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…