ProgramGuru
| Input Tree | Diagonal Traversal Output | Description |
|---|---|---|
| [8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13]
|
[[8, 10, 14], [3, 6, 7, 13], [1, 4]] | Standard tree with multiple diagonals including both left and right subtrees |
| [1]
|
[[1]] | Single-node tree with only the root |
| [] | [] | Empty binary tree with no nodes |
| [1, 2, null, 3, null, 4]
|
[[1], [2], [3], [4]] | Left-skewed binary tree with only left children |
| [1, null, 2, null, 3, null, 4]
|
[[1, 2, 3, 4]] | Right-skewed binary tree, all nodes fall in the same diagonal |
| [10, 20, 30, 40, null, null, 50]
|
[[10, 30, 50], [20], [40]] | Tree with mixed left and right children forming three diagonals |
We are given a binary tree and asked to perform a diagonal traversal. In a diagonal traversal, nodes that lie on the same diagonal from top-right to bottom-left are grouped together.
The idea is that if you start at the root and keep moving right, all the nodes you encounter are on the same diagonal. If a node has a left child, it belongs to the next diagonal and should be processed later.
We want to return a single list of nodes as they appear in a diagonal-wise order, starting from the top-rightmost diagonal.
8
/ 3 10
/ 1 6 14
/ /
4 7 13
We'll traverse this tree diagonally.
We use a queue to keep track of the left children we encounter (they belong to the next diagonal).
We start by pushing the root node (8) into the queue.
So the first diagonal is: 8, 10, 14
Second diagonal: 3, 6, 7, 13
Third diagonal: 1, 4
Final result after combining diagonals in order: [8, 10, 14, 3, 6, 7, 13, 1, 4]
If the tree is empty (i.e., the root node is null), then there are no nodes to traverse. Return: []
If the tree has only one node (like 1), then the diagonal traversal is simply [1]
In a left-skewed tree (each node only has a left child), each node will belong to a separate diagonal.
5
/
4
/
3
Output: [5, 4, 3]
In a right-skewed tree, all nodes lie on the same diagonal.
1
2
3
Output: [1, 2, 3]
Diagonal traversal is a unique way to explore a binary tree that isn't covered by typical traversals like inorder, preorder, or level order. By using a queue and traversing right while queueing left children, we maintain control over the diagonals in an intuitive and iterative way. Make sure to always account for edge cases like empty or skewed trees for a complete and robust solution.
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Hello from C!\n");
return 0;
}
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗