Replace node with depth in a binary tree | CPP program to replace every key value with its depth . ; A tree node structure ; Utility function to create a new Binary Tree node ; Helper function replaces the data with depth Note : Default value of level is 0 for root . ; Base Case ; Replace data with current depth ; A utility function to print inorder traversal of a Binary Tree ; Driver function to test above functions ; Constructing tree given in the above figure
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void replaceNode ( struct Node * node , int level = 0 ) { if ( node == NULL ) return ; node -> data = level ; replaceNode ( node -> left , level + 1 ) ; replaceNode ( node -> right , level + 1 ) ; } void printInorder ( struct Node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; cout << node -> data << " ▁ " ; printInorder ( node -> right ) ; } int main ( ) { struct Node * root = new struct Node ; 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 STRNEWLINE " ; printInorder ( root ) ; replaceNode ( root ) ; cout << endl ; cout << " After ▁ Replacing ▁ Nodes STRNEWLINE " ; printInorder ( root ) ; return 0 ; }