Replace Node With Depth Problem Statement

For a given Binary Tree of integers, replace each of its data with the depth of the tree. The root is at depth 0, hence the root data is updated with 0. Replicate the same further going down the tree in the depth of the given tree.

Input:

The first line contains an integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. The first line of each test case contains the elements of the tree in level order form separated by a single space. If any node does not have a left or right child, take -1 in its place.

Output:

For each test case, print the inorder traversal of the tree where each node is replaced by the depth of the current node. Output for every test case will be denoted in a separate line.

Example:

Input: 
1
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output: 
2 1 2 0 2 1 2

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 1000
  • -10^9 <= data <= 10^9
  • Time limit: 1 sec
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
AnswerBot
4mo

Replace each node in a binary tree with its depth starting from root as 0.

  • Traverse the binary tree in inorder fashion and update each node's data with its depth.

  • Start with depth 0 for the root node an...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Intern Interview Questions Asked at Goldman Sachs

Q. Write the code for Merge Sort.
Q. Given a sorted array of integers nums and an integer target, write a function to...read more
Q. Rectangle Area Problem Statement You are provided with a list of rectangles, eac...read more
Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits