Kth node in Diagonal Traversal of Binary Tree in C++


In this tutorial, we are going to write a program that finds the k-th node in the diagonal traversal of a binary tree.

Let's see the steps to solve the problem.

  • Initialise the binary tree with some sample data.
  • Initialise the number k.
  • Traverse the binary tree diagonally using the data structure queue.
    • Decrement the value of k on each node.
    • Return the node when k becomes 0.
  • Return -1 if there is no such node.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node *left, *right;
};
Node* getNewNode(int data) {
   Node* node = (Node*)malloc(sizeof(Node));
   node->data = data;
   node->left = node->right = NULL;
   return node;
}
int findDiagonalKthElement(Node* root, int k) {
   if (root == NULL || k == 0) {
      return -1;
   }
   int result = -1;
   queue<Node*> q;
   q.push(root);
   q.push(NULL);
   while (!q.empty()) {
      Node* temp = q.front();
      q.pop();
      if (temp == NULL) {
         if (q.empty()) {
            if (k == 0) {
               return result;
            }else {
               break;
            }
         }
         q.push(NULL);
      }else {
         while (temp) {
            if (k == 0) {
               return result;
            }
            k--;
            result = temp->data;
            if (temp->left) {
               q.push(temp->left);
            }
            temp = temp->right;
         }
      }
   }
   return -1;
}
int main() {
   Node* root = getNewNode(10);
   root->left = getNewNode(5);
   root->right = getNewNode(56);
   root->left->left = getNewNode(3);
   root->left->right = getNewNode(22);
   root->right->right = getNewNode(34);
   root->right->right->left = getNewNode(45);
   root->left->right->left = getNewNode(67);
   root->left->right->right = getNewNode(100);
   int k = 9;
   cout << findDiagonalKthElement(root, k) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

67

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 09-Apr-2021

50 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements