Consider lines of slope -1 passing between nodes. Given a Binary Tree, print all diagonal elements in a binary tree belonging to the same line.
Input : Root of below tree
Output : Diagonal Traversal of binary tree : 8 10 14 3 6 7 13 1 4
The idea is to use a map. We use different slope distances and use them as key in the map. Value in the map is a vector (or dynamic array) of nodes. We traverse the tree to store values in the map. Once map is built, we print the contents of it.
Below is the implementation of the above idea.
Diagonal Traversal of binary tree : 8 10 14 3 6 7 13 1 4
This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Kth node in Diagonal Traversal of Binary Tree
- Iterative diagonal traversal of binary tree
- Level order traversal of Binary Tree using Morris Traversal
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Zigzag (or diagonal) traversal of Matrix
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Diagonal Sum of a Binary Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Cartesian tree from inorder traversal | Segment Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Construct Special Binary Tree from given Inorder traversal
- Boundary Traversal of binary tree
- Perfect Binary Tree Specific Level Order Traversal
- Check if a given array can represent Preorder Traversal of Binary Search Tree
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Density of Binary Tree in One Traversal
- Check if the given array can represent Level Order Traversal of Binary Search Tree
- Postorder traversal of Binary Tree without recursion and without stack