Skip to content

Commit d837e43

Browse files
authored
Create Replace Node with Depth
1 parent 1910a95 commit d837e43

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
For a given a Binary Tree of integers, replace each of its data with the depth of the tree.
3+
Root is at depth 0, hence the root data is updated with 0. Replicate the same further going down the in the depth of the given tree.
4+
The modified tree will be printed in the in-order fashion.
5+
6+
Input Format:
7+
The first and the only line of input will contain the node data, all separated by a single space.
8+
Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.
9+
10+
Output Format:
11+
The first and the only line of output prints the updated tree in the in-order fashion.
12+
Note: You are not required to print anything explicitly. It has already been taken care of.
13+
14+
Constraints:
15+
1 <= N <= 10^5
16+
Where N is the total number of nodes in the binary tree.
17+
Time Limit: 1sec
18+
19+
Sample Input 1:
20+
2 35 10 2 3 5 2 -1 -1 -1 -1 -1 -1 -1 -1
21+
Sample Output 1:
22+
2 1 2 0 2 1 2
23+
24+
Sample Input 2:
25+
1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1
26+
Sample Output 2:
27+
2 1 2 0 2 1 2
28+
*/
29+
/*
30+
31+
Following is the structure used to represent the Binary Tree Node
32+
33+
class BinaryTreeNode<T> {
34+
T data;
35+
BinaryTreeNode<T> left;
36+
BinaryTreeNode<T> right;
37+
38+
public BinaryTreeNode(T data) {
39+
this.data = data;
40+
this.left = null;
41+
this.right = null;
42+
}
43+
}
44+
45+
*/
46+
47+
public class Solution {
48+
49+
public static void changeToDepthTree(BinaryTreeNode<Integer> root) {
50+
//Your code goes here
51+
changeToDepthTree(root,0);
52+
}
53+
54+
public static void changeToDepthTree(BinaryTreeNode<Integer> root, int depth)
55+
{
56+
if (root==null)
57+
{
58+
return;
59+
}
60+
root.data=depth;
61+
changeToDepthTree(root.left,depth+1);
62+
changeToDepthTree(root.right,depth+1);
63+
}
64+
65+
}

0 commit comments

Comments
 (0)