Find the kth node in vertical order traversal of a Binary Tree
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:
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.