Given a Binary Tree, the task is to print the diagonal traversal of the binary tree. Note: If the diagonal element are present in two different subtrees, then left subtree diagonal element should be taken first and then right subtree.
[Expected Approach - 1] Using Queue with delimiter - O(n) Time and O(n) Space
The idea is to traverse the binary tree in level order manner using a queue. Push the root node and null pointer into the queue. For each node (starting from root), append its value to the resultant list. Push its left child node into queue if it exists, and set it to its right child node. If the current node is null, it means the starting of the next diagonal. So set the current node to the front node of the queue and pop from queue.
Below is the implementation of the above approach:
Output
8 10 14 3 6 7 13 1 4
Time Complexity: O(n), where n is the total number of nodes in the binary tree. Auxiliary Space: O(n)
[Expected Approach - 2] Using Queue without delimiter - O(n) Time and O(n) Space