VOOZH about

URL: https://www.geeksforgeeks.org/dsa/iterative-diagonal-traversal-binary-tree/

⇱ Iterative diagonal traversal of binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Iterative diagonal traversal of binary tree

Last Updated : 26 Sep, 2024

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.

Example:

Input:

👁 Diagonal-Traversal-of-binary-tree

Output: 8 10 14 3 6 7 13 1 4
Explanation: The above is the diagonal elements in a binary tree that belong to the same line.

[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

The idea is similar to level order traversal, use a queue, but here delimiter is not used. Little modification is to be done. 

  • if(curr.left != null), then add it to the queue and move curr pointer to right of curr.
  • if curr = null, then remove a node 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)

Related articles:

Comment
Article Tags: