-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
33 lines (28 loc) · 846 Bytes
/
Copy pathSolution.java
File metadata and controls
33 lines (28 loc) · 846 Bytes
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
class Solution {
public TreeNode addOneRow(TreeNode root, int val, int depth) {
if (depth == 1) {
TreeNode node = new TreeNode(val);
node.left = root;
return node;
}
dfs(root, null, true, val, 1, depth);
return root;
}
private void dfs(TreeNode curr, TreeNode p, boolean left, int val, int d, int depth) {
if (d == depth) {
if (left) {
p.left = new TreeNode(val);
p.left.left = curr;
} else {
p.right = new TreeNode(val);
p.right.right = curr;
}
return;
}
if (curr == null) {
return;
}
dfs(curr.left, curr, true, val, d + 1, depth);
dfs(curr.right, curr, false, val, d + 1, depth);
}
}