Replace node with depth in a binary tree

02 May, 2022
Given a binary tree, replace each node with its depth value. For example, consider the following tree. Root is at depth 0, change its value to 0 and next level nodes are at depth 1 and so on.  
       3                       0
      /  \                    /   \
     2    5      == >;         1     1
   /   \                   /   \
  1     4                 2     2
 
The idea is to traverse tree starting from root. While traversing pass depth of node as parameter. We can track depth by passing it as 0 for root and one-plus-current-depth for children.Below is the implementation of the idea.  
C++
Java
Python3
C#
Javascript
// CPP program to replace every key value// with its depth.#include<bits/stdc++.h>using namespace std; /* A tree node structure */struct Node{    int data;    struct Node *left, *right;}; /* Utility function to create a   new Binary Tree node */struct Node* newNode(int data){    Node *temp = new Node;    temp->data = data;    temp->left = temp->right = NULL;       return temp;} // Helper function replaces the data with depth// Note : Default value of level is 0 for root.void replaceNode(struct Node *node, int level=0){    // Base Case    if (node == NULL)        return;     // Replace data with current depth    node->data = level;     replaceNode(node->left, level+1);    replaceNode(node->right, level+1);} // A utility function to print inorder// traversal of a Binary Treevoid printInorder(struct Node* node){     if (node == NULL)          return;     printInorder(node->left);     cout << node->data <<" ";     printInorder(node->right);} /* Driver function to test above functions */int main(){    struct Node *root = new struct Node;     /* Constructing tree given in       the above figure */    root = newNode(3);    root->left = newNode(2);    root->right = newNode(5);    root->left->left = newNode(1);    root->left->right = newNode(4);         cout << "Before Replacing Nodes\n";       printInorder(root);    replaceNode(root);     cout << endl;         cout << "After Replacing Nodes\n";    printInorder(root);         return 0;}
// Java program to replace every key value// with its depth.class GfG { /* A tree node structure */static class Node{    int data;    Node left, right;} /* Utility function to create anew Binary Tree node */static Node newNode(int data){    Node temp = new Node();    temp.data = data;    temp.left = null;    temp.right = null;        return temp;} // Helper function replaces the data with depth// Note : Default value of level is 0 for root.static void replaceNode(Node node, int level){    // Base Case    if (node == null)        return;     // Replace data with current depth    node.data = level;     replaceNode(node.left, level+1);    replaceNode(node.right, level+1);} // A utility function to print inorder// traversal of a Binary Treestatic void printInorder(Node node){    if (node == null)        return;    printInorder(node.left);    System.out.print(node.data + " ");    printInorder(node.right);} /* Driver function to test above functions */public static void main(String[] args){    Node root = new Node();     /* Constructing tree given in    the above figure */    root = newNode(3);    root.left = newNode(2);    root.right = newNode(5);    root.left.left = newNode(1);    root.left.right = newNode(4);         System.out.println("Before Replacing Nodes");        printInorder(root);    replaceNode(root, 0);    System.out.println();         System.out.println("After Replacing Nodes");    printInorder(root);     }}
# Python3 program to replace every key# value with its depth. class newNode:    def __init__(self, data):        self.data = data        self.left = self.right = None # Helper function replaces the data with depth# Note : Default value of level is 0 for root.def replaceNode(node, level = 0):         # Base Case    if (node == None):        return     # Replace data with current depth    node.data = level     replaceNode(node.left, level + 1)    replaceNode(node.right, level + 1) # A utility function to print inorder# traversal of a Binary Treedef printInorder(node):    if (node == None):        return    printInorder(node.left)    print(node.data, end = " ")    printInorder(node.right) # Driver Codeif __name__ == '__main__':     # Constructing tree given in    # the above figure    root = newNode(3)    root.left = newNode(2)    root.right = newNode(5)    root.left.left = newNode(1)    root.left.right = newNode(4)         print("Before Replacing Nodes")        printInorder(root)    replaceNode(root)         print()    print("After Replacing Nodes")    printInorder(root) # This code is contributed by PranchalK
// C# program to replace every key value// with its depth.using System; public class GfG{     /* A tree node structure */    public class Node    {        public int data;        public Node left, right;    }     /* Utility function to create a    new Binary Tree node */    static Node newNode(int data)    {        Node temp = new Node();        temp.data = data;        temp.left = null;        temp.right = null;            return temp;    }     // Helper function replaces the data with depth    // Note : Default value of level is 0 for root.    static void replaceNode(Node node, int level)    {        // Base Case        if (node == null)            return;         // Replace data with current depth        node.data = level;         replaceNode(node.left, level + 1);        replaceNode(node.right, level + 1);    }     // A utility function to print inorder    // traversal of a Binary Tree    static void printInorder(Node node)    {        if (node == null)            return;        printInorder(node.left);        Console.Write(node.data + " ");        printInorder(node.right);    }     /* Driver code*/    public static void Main(String[] args)    {        Node root = new Node();         /* Constructing tree given in        the above figure */        root = newNode(3);        root.left = newNode(2);        root.right = newNode(5);        root.left.left = newNode(1);        root.left.right = newNode(4);         Console.WriteLine("Before Replacing Nodes");            printInorder(root);        replaceNode(root, 0);        Console.WriteLine();         Console.WriteLine("After Replacing Nodes");        printInorder(root);    }} // This code is contributed Rajput-Ji
<script>     // JavaScript program to replace every    // key value with its depth.         class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }           /* Utility function to create a    new Binary Tree node */    function newNode(data)    {        let temp = new Node(data);        return temp;    }     // Helper function replaces the data with depth    // Note : Default value of level is 0 for root.    function replaceNode(node, level)    {        // Base Case        if (node == null)            return;         // Replace data with current depth        node.data = level;         replaceNode(node.left, level+1);        replaceNode(node.right, level+1);    }     // A utility function to print inorder    // traversal of a Binary Tree    function printInorder(node)    {        if (node == null)            return;        printInorder(node.left);        document.write(node.data + " ");        printInorder(node.right);    }         let root = new Node();       /* Constructing tree given in    the above figure */    root = newNode(3);    root.left = newNode(2);    root.right = newNode(5);    root.left.left = newNode(1);    root.left.right = newNode(4);           document.write("Before Replacing Nodes" + "</br>");        printInorder(root);    replaceNode(root, 0);    document.write("</br>");    document.write("</br>");           document.write("After Replacing Nodes" + "</br>");    printInorder(root); </script>
Output:  
Before Replacing Nodes
1 2 4 3 5 

After Replacing Nodes
2 1 2 0 1 
 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Replace node with depth in a binary tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReplace node with depth in a binary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=p5_P7Rx-98A" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Chhavi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
 
prerna saini
PranchalKatiyar
Rajput-Ji
rameshtravel07
simmytarika5
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree
Lowest Common Ancestor in a Binary Tree | Set 1
Decision Tree
Diagonal Traversal of Binary Tree