Given a binary tree and an integer k, the task is to print the kth node in the vertical order traversal of binary tree.If no such node exists then print -1.
The vertical order traversal of a binary tree means to print it vertically.
Input: 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 k = 3 Output: 1 The vertical order traversal of above tree is: 4 2 1 5 6 3 8 7 9 Input: 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 k = 13 Output: -1
Approach: The idea is to perform vertical order traversal and check if the current node is the kth node then print its value, if number of nodes in the tree is less than K then print -1.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Deletion of a given node K in a Binary Tree using Level Order Traversal
- Create a binary tree from post order traversal and leaf node array
- Find n-th node in Preorder traversal of a Binary Tree
- Find n-th node in Postorder traversal of a Binary Tree
- Print a Binary Tree in Vertical Order | Set 1
- Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
- Flatten Binary Tree in order of Level Order Traversal
- Flatten binary tree in order of post-order traversal
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Middle To Up-Down Order traversal of a Binary Tree
- Flatten Binary Tree in order of Zig Zag traversal
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
- Density of Binary Tree using Level Order Traversal
- Boundary Level order traversal of a 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 : rituraj_jain