Given a binary tree and a value K. The task is to print the k-th node in the diagonal traversal of the binary tree. If no such node exists then print -1.
Input : 8 / \ 3 10 / / \ 1 6 14 / \ / 4 7 13 k = 5 Output : 6 Diagonal Traversal of the above tree is: 8 10 14 3 6 7 13 1 4 Input : 1 / \ 2 3 / \ 4 5 k = 7 Output : -1
Approach: The idea is to perform the diagonal traversal of the binary tree until K nodes are visited in the diagonal traversal. While traversing for each node visited decrement the value of variable K and return the current node when the value of K becomes zero. If the diagonal traversal does not contain at least K nodes, return -1.
Below is the implementation of the above approach:
- Diagonal Traversal of Binary Tree
- Iterative diagonal traversal of binary tree
- Find n-th node in Postorder traversal of a Binary Tree
- Find n-th node in Preorder traversal of a Binary Tree
- Find the kth node in vertical order traversal of a Binary Tree
- Print cousins of a given node in Binary Tree | Single Traversal
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Diagonal Sum of a Binary Tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
- Zig-Zag traversal of a Binary Tree using Recursion
- Density of Binary Tree in One Traversal
- Boundary Traversal of binary tree
- Clockwise Spiral Traversal of Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : andrew1234