Iterative program to find distance of a node from root

Given the root of a binary tree and a key x in it, find the distance of the given key from the root node. Dis­tance means num­ber of edges between two nodes.

Examples:

Input : x = 45,
   5 is Root of below tree
        5
      /    \
    10      15
    / \    /  \
  20  25  30   35
       \
       45
Output : Distance = 3             
There are three edges on path
from root to 45.

For more understanding of question,
in above tree distance of 35 is two
and distance of 10 is 1.

Related Problem: Recursive program to find distance of node from root.

Iterative Approach :

  • Use level order traversal to traverse the tree iteratively using a queue.
  • Keep a variable levelCount to maintain the track of current level.
  • To do this, every time on moving to the next level, while pushing a NULL node to the queue also increment the value of the variable levelCount so that it stores the current level number.
  • While traversing the tree, check if any node at the current level matches with the given key.
  • If yes, then return levelCount.

Below is the implementation of above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find distance of a given
// node from root.
#include <bits/stdc++.h>
using namespace std;
  
// A Binary Tree Node
struct Node {
    int data;
    Node *left, *right;
};
  
// A utility function to create a new Binary
// Tree Node
Node* newNode(int item)
{
    Node* temp = new Node;
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}
  
/* Function to find distance of a node from root
*  root : root of the Tree
*  key : data whose distance to be calculated
*/
int findDistance(Node* root, int key)
{
  
    // base case
    if (root == NULL) {
        return -1;
    }
  
    // If the key is present at root,
    // distance is zero
    if (root->data == key)
        return 0;
  
    // Iterating through tree using BFS
    queue<Node*> q;
  
    // pushing root to the queue
    q.push(root);
  
    // pushing marker to the queue
    q.push(NULL);
  
    // Variable to store count of level
    int levelCount = 0;
  
    while (!q.empty()) {
  
        Node* temp = q.front();
        q.pop();
  
        // if node is marker, push marker to queue
        // else, push left and right (if exists)
        if (temp == NULL && !q.empty()) {
            q.push(NULL);
  
            // Increment levelCount, while moving
            // to new level
            levelCount++;
        }
        else if (temp != NULL) {
  
            // If node at current level is Key,
            // return levelCount
            if (temp->data == key)
                return levelCount;
  
            if (temp->left)
                q.push(temp->left);
  
            if (temp->right)
                q.push(temp->right);
        }
    }
  
    // If key is not found
    return -1;
}
  
// Driver Code
int main()
{
    Node* root = newNode(5);
    root->left = newNode(10);
    root->right = newNode(15);
    root->left->left = newNode(20);
    root->left->right = newNode(25);
    root->left->right->right = newNode(45);
    root->right->left = newNode(30);
    root->right->right = newNode(35);
  
    cout << findDistance(root, 45);
  
    return 0;
}

chevron_right


Output:

3


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.