Replace node with depth in a binary tree | Java 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
class GfG { static class Node { int data ; Node left , right ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = null ; temp . right = null ; return temp ; } static void replaceNode ( Node node , int level ) { if ( node == null ) return ; node . data = level ; replaceNode ( node . left , level + 1 ) ; replaceNode ( node . right , level + 1 ) ; } static void printInorder ( Node node ) { if ( node == null ) return ; printInorder ( node . left ) ; System . out . print ( node . data + " ▁ " ) ; printInorder ( node . right ) ; } public static void main ( String [ ] args ) { Node root = new Node ( ) ; 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 ) ; } }