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.
Examples:Â
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:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Structure for a binary tree nodestruct Node {Â Â Â Â int key;Â Â Â Â Node *left, *right;};Â
// A utility function to create a new nodeNode* newNode(int key){Â Â Â Â Node* node = new Node;Â Â Â Â node->key = key;Â Â Â Â node->left = node->right = NULL;Â Â Â Â return node;}Â
// Function to find kth node// in vertical order traversalint KNodeVerticalOrder(Node* root, int k){    // Base case    if (!root || k == 0)        return -1;Â
    int n = 0;Â
    // Variable to store kth node    int k_node = -1;Â
    // Create a map and store vertical order in    // map    map<int, vector<int> > m;    int hd = 0;Â
    // Create queue to do level order traversal    // Every item of queue contains node and    // horizontal distance    queue<pair<Node*, int> > que;    que.push(make_pair(root, hd));Â
    while (!que.empty()) {        // Pop from queue front        pair<Node*, int> temp = que.front();        que.pop();        hd = temp.second;        Node* node = temp.first;Â
        // Insert this node's data in vector of hash        m[hd].push_back(node->key);Â
        if (node->left != NULL)            que.push(make_pair(node->left, hd - 1));        if (node->right != NULL)            que.push(make_pair(node->right, hd + 1));    }Â
    // Traverse the map and find kth    // node    map<int, vector<int> >::iterator it;    for (it = m.begin(); it != m.end(); it++) {        for (int i = 0; i < it->second.size(); ++i) {            n++;            if (n == k)                return (it->second[i]);        }    }Â
    if (k_node == -1)        return -1;}Â
// Driver codeint main(){Â Â Â Â Node* root = newNode(1);Â Â Â Â root->left = newNode(2);Â Â Â Â root->right = newNode(3);Â Â Â Â root->left->left = newNode(4);Â Â Â Â root->left->right = newNode(5);Â Â Â Â root->right->left = newNode(6);Â Â Â Â root->right->right = newNode(7);Â Â Â Â root->right->left->right = newNode(8);Â Â Â Â root->right->right->right = newNode(9);Â Â Â Â root->right->right->left = newNode(10);Â Â Â Â root->right->right->left->right = newNode(11);Â Â Â Â root->right->right->left->right->right = newNode(12);Â
    int k = 5;    cout << KNodeVerticalOrder(root, k);Â
    return 0;} |
Java
// Java implementation of the approachimport java.util.ArrayList;import java.util.HashMap;import java.util.LinkedList;import java.util.Map;import java.util.Queue;import java.util.SortedMap;import java.util.TreeMap;Â
class GFG{Â
// Structure for a binary tree nodestatic class Node {Â Â Â Â int key;Â Â Â Â Node left, right;Â
    public Node(int key)     {        this.key = key;        this.left = this.right = null;    }};Â
static class Pair{Â Â Â Â Node first;Â Â Â Â int second;Â
    public Pair(Node first, int second)     {        this.first = first;        this.second = second;    }}Â
// Function to find kth node// in vertical order traversalstatic int KNodeVerticalOrder(Node root, int k) {         // Base case    if (root == null || k == 0)        return -1;Â
    int n = 0;Â
    // Variable to store kth node    int k_node = -1;Â
    // Create a map and store vertical order in    // map    SortedMap<Integer,     ArrayList<Integer>> m = new TreeMap<Integer,                               ArrayList<Integer>>();    int hd = 0;Â
    // Create queue to do level order traversal    // Every item of queue contains node and    // horizontal distance    Queue<Pair> que = new LinkedList<>();    que.add(new Pair(root, hd));Â
    while (!que.isEmpty())    {                 // Pop from queue front        Pair temp = que.poll();        hd = temp.second;        Node node = temp.first;Â
        // Insert this node's data in        // vector of hash        if (m.get(hd) == null)            m.put(hd, new ArrayList<>());                     m.get(hd).add(node.key);Â
        if (node.left != null)            que.add(new Pair(node.left, hd - 1));        if (node.right != null)            que.add(new Pair(node.right, hd + 1));    }Â
    // Traverse the map and find kth    // node    for(Map.Entry<Integer,         ArrayList<Integer>> it : m.entrySet())    {        for(int i = 0;                 i < it.getValue().size();                i++)        {            n++;            if (n == k)             {                return it.getValue().get(i);            }        }    }Â
    if (k_node == -1)        return -1;             return 0;}Â
// Driver codepublic static void main(String[] args){Â Â Â Â Node root = new Node(1);Â Â Â Â root.left = new Node(2);Â Â Â Â root.right = new Node(3);Â Â Â Â root.left.left = new Node(4);Â Â Â Â root.left.right = new Node(5);Â Â Â Â root.right.left = new Node(6);Â Â Â Â root.right.right = new Node(7);Â Â Â Â root.right.left.right = new Node(8);Â Â Â Â root.right.right.right = new Node(9);Â Â Â Â root.right.right.left = new Node(10);Â Â Â Â root.right.right.left.right = new Node(11);Â Â Â Â root.right.right.left.right.right = new Node(12);Â
    int k = 5;         System.out.println(KNodeVerticalOrder(root, k));Â
}}Â
 // This code is contributed by sanjeev2552 |
Python3
# Python3 implementation of the approach Â
# Tree node structure class Node:         def __init__(self, key):        self.key = key        self.left = None        self.right = NoneÂ
# Function to find kth node # in vertical order traversal def KNodeVerticalOrder(root, k): Â
    # Base case     if not root or k == 0:        return -1Â
    n = 0         # Variable to store kth node     k_node = -1Â
    # Create a map and store     # vertical order in map     m = {}    hd = 0Â
    # Create queue to do level order     # traversal Every item of queue contains     # node and horizontal distance     que = []     que.append((root, hd)) Â
    while len(que) > 0:                  # Pop from queue front         temp = que.pop(0)         hd = temp[1]        node = temp[0] Â
        # Insert this node's data in vector of hash         if hd not in m: m[hd] = []        m[hd].append(node.key) Â
        if node.left != None:             que.append((node.left, hd - 1))         if node.right != None:             que.append((node.right, hd + 1)) Â
    # Traverse the map and find kth node     for it in sorted(m):         for i in range(0, len(m[it])):             n += 1            if n == k:                 return m[it][i] Â
    if k_node == -1:        return -1Â
# Driver code if __name__ == "__main__": Â
    root = Node(1)     root.left = Node(2)     root.right = Node(3)     root.left.left = Node(4)     root.left.right = Node(5)     root.right.left = Node(6)     root.right.right = Node(7)     root.right.left.right = Node(8)     root.right.right.right = Node(9)     root.right.right.left = Node(10)     root.right.right.left.right = Node(11)     root.right.right.left.right.right = Node(12) Â
    k = 5    print(KNodeVerticalOrder(root, k)) Â
# This code is contributed by Rituraj Jain |
C#
// C# implementation of the approachusing System.Collections.Generic;using System.Collections;using System;class GFG{Â Â // Structure for a // binary tree nodeclass Node {Â Â public int key;Â Â public Node left, Â Â Â Â Â Â Â Â Â Â Â Â Â Â right;Â
  public Node(int key)   {    this.key = key;    this.left =     this.right = null;  }};  class Pair{  public Node first;  public int second;Â
  public Pair(Node first,               int second)   {    this.first = first;    this.second = second;  }}  // Function to find kth node// in vertical order traversalstatic int KNodeVerticalOrder(Node root,                               int k) {      // Base case  if (root == null || k == 0)    return -1;Â
  int n = 0;Â
  // Variable to store  // kth node  int k_node = -1;Â
  // Create a map and store   // vertical order in map  SortedDictionary<int,                   ArrayList> m =                    new SortedDictionary<int,                                        ArrayList>();  int hd = 0;Â
  // Create queue to do level order   // traversal. Every item of queue   // contains node and horizontal   // distance  Queue que = new Queue(); Â
  que.Enqueue(new KeyValuePair<Node,                               int>(root,                                    hd));Â
  while(que.Count != 0)  {    // Pop from queue front    KeyValuePair<Node,                 int> temp =                  (KeyValuePair<Node,                               int>)que.Dequeue();    hd = temp.Value;    Node node = temp.Key;Â
    // Insert this node's data in    // vector of hash    if (!m.ContainsKey(hd))      m[hd] = new ArrayList();Â
    m[hd].Add(node.key);Â
    if (node.left != null)      que.Enqueue(      new KeyValuePair<Node,                       int>(node.left,                             hd - 1));    if (node.right != null)      que.Enqueue(      new KeyValuePair<Node,                       int>(node.right,                            hd + 1));  }Â
  // Traverse the map and find kth  // node  foreach(KeyValuePair<int,                       ArrayList> it in m)  {    for(int i = 0; i < it.Value.Count; i++)    {      n++;      if (n == k)       {        return (int)it.Value[i];      }    }  }Â
  if (k_node == -1)    return -1;Â
  return 0;}Â
// Driver codepublic static void Main(string[] args){Â Â Node root = new Node(1);Â Â root.left = new Node(2);Â Â root.right = new Node(3);Â Â root.left.left = new Node(4);Â Â root.left.right = new Node(5);Â Â root.right.left = new Node(6);Â Â root.right.right = new Node(7);Â Â root.right.left.right = new Node(8);Â Â root.right.right.right = new Node(9);Â Â root.right.right.left = new Node(10);Â Â root.right.right.left.right = new Node(11);Â Â root.right.right.left.right.right = new Node(12);Â
  int k = 5;  Console.Write(KNodeVerticalOrder(root, k));}}Â
// This code is contributed by Rutvik_56 |
Javascript
<script>    //JavaScript code for the above approach    class Tree {  constructor(key) {    this.key = key;    this.left = null;    this.right = null;  }}Â
// Function to find kth node// in vertical order traversalfunction KNodeVerticalOrder(root, k) {  // Base case  if (!root || k == 0) return -1;Â
  let n = 0;Â
  // Variable to store kth node  let kNode = -1;Â
  // Create a map and store vertical order in  // map  let m = new Map();  let hd = 0;Â
  // Create queue to do level order traversal  // Every item of queue contains node and  // horizontal distance  let que = [];  que.push([root, hd]);Â
  while (que.length > 0) {    // Pop from queue front    let [node, hd] = que.shift();Â
    // Insert this node's data in vector of hash    if (!m.has(hd)) m.set(hd, []);    m.get(hd).push(node.key);Â
    if (node.left != null) que.push([node.left, hd - 1]);    if (node.right != null) que.push([node.right, hd + 1]);  }Â
  // Traverse the map and find kth  // node  for (let [key, values] of m) {    for (let i = 0; i < values.length; ++i) {      n++;      if (n == k) return 2*values[i];    }  }Â
  if (kNode == -1) return -1;}Â
// Examplelet root = new Tree(1);root.left = new Tree(2);root.right = new Tree(3);root.left.left = new Tree(4);root.left.right = new Tree(5);root.right.left = new Tree(6);root.right.right = new Tree(7);root.right.left.right = new Tree(8);root.right.right.right = new Tree(9);root.right.right.left = new Tree(10);root.right.right.left.right = new Tree(11);root.right.right.left.right.right = new Tree(12);Â
let k = 5;document.write(KNodeVerticalOrder(root, k));Â
Â
 // This code is contributed by Potta LokeshÂ
  </script> |
Output:Â
6
Â
Time Complexity: O(N)
Auxiliary Space: O(N)Â
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



