forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd One Row to Tree.java
More file actions
43 lines (37 loc) · 1.01 KB
/
Add One Row to Tree.java
File metadata and controls
43 lines (37 loc) · 1.01 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode addOneRow(TreeNode root, int v, int d) {
if (d == 1) {
TreeNode t = new TreeNode(v);
t.left = root;
return t;
}
helper(root, v, d, 1);
return root;
}
private void helper(TreeNode root, int v, int d, int currLevel) {
if (currLevel == d-1) {
TreeNode t1 = new TreeNode(v);
TreeNode t2 = new TreeNode(v);
t1.left = root.left;
t2.right = root.right;
root.left = t1;
root.right = t2;
return;
}
if (root.left != null) {
helper(root.left, v, d, currLevel + 1);
}
if (root.right != null) {
helper(root.right, v, d, currLevel + 1);
}
}
}