-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReplaceNodeWithDepth2.java
More file actions
60 lines (53 loc) · 1.61 KB
/
ReplaceNodeWithDepth2.java
File metadata and controls
60 lines (53 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Replace node with depth
// Send Feedback
// In a given Generic Tree, replace each node with its depth value. You need to
// just update the data of each node, no need to return or print anything. Depth
// of a node is defined as the distance of the node from root. You may assume
// that depth of root node is 0.
// Input format :
// Line 1 : Elements in level order form separated by space (as per done in
// class) in the below given order:
// node_data, n (number of children of node), n children, and so on for every
// element `
// Output format :
// Print the depth of each node level wise.
// Sample Input 1 :
// 10 3 20 30 40 2 40 50 0 0 0 0
// Representation of Input:
// Sample Output 1 : (Level wise, each level in new line)
// 0
// 1 1 1
// 2 2
// Explanation
// Since root is 10 , so it's depth is 0
// Node 20, 30 , 40 are present at 1st level , so their depth is 1.
// Node 40,50 are present at 2nd level, so their depth is 2.
public class Solution {
/*
* TreeNode structure
*
* class TreeNode<T> {
* T data;
* ArrayList<TreeNode<T>> children;
*
* TreeNode(T data){
* this.data = data;
* children = new ArrayList<TreeNode<T>>();
* }
* }
*/
public static void helper(TreeNode<Integer> root, int k) {
if (root == null) {
return;
}
root.data = k;
k = k + 1;
for (int i = 0; i < root.children.size(); i++) {
helper(root.children.get(i), k);
}
}
public static void replaceWithDepthValue(TreeNode<Integer> root) {
// Write your code here
helper(root, 0);
}
}