Open In App

Replace node with depth in a binary tree

Last Updated : 21 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Share
1 Like
Like
Report

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

Output
Before Replacing Nodes
1 2 4 3 5 
After Replacing Nodes
2 1 2 0 1 

Time Complexity: O(n) 
Space Complexity: If we don't consider size of stack for function calls then O(1) otherwise O(h)

Iterative Approach(Using Queue data structure):
Follow the below steps to solve the above problem:
1) Perform level order traversal with the help of queue data structure.
2) At each level keep track to level(indexing 0) and replace all nodes data of current level to level value.
3) Print the Inorder traversal of resultant tree.
Below is the implementation of above approach:

C++
Java Python3 C# JavaScript

Output
Before Replacing Nodes
1 2 4 3 5 
After Replacing Nodes
2 1 2 0 1 

Time Complexity: O(N) where N is the number of nodes in given binary tree
Auxiliary Space: O(N) due to queue data structure


Replace node with depth in a binary tree
Article Tags :
Practice Tags :

Similar Reads