java: add «623. Add One Row to Tree»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
badc57445c
commit
d5634c4d42
1 changed files with 35 additions and 0 deletions
35
java/add-one-row-to-tree.java
Normal file
35
java/add-one-row-to-tree.java
Normal file
|
@ -0,0 +1,35 @@
|
|||
class Solution {
|
||||
private enum Side {
|
||||
Left,
|
||||
Right
|
||||
}
|
||||
|
||||
private TreeNode addOneRow(int depth, int val, TreeNode node, int currentDepth, Side s) {
|
||||
if (depth == currentDepth) {
|
||||
var newRoot = new TreeNode(val);
|
||||
switch (s) {
|
||||
case Left:
|
||||
newRoot.left = node;
|
||||
break;
|
||||
case Right:
|
||||
newRoot.right = node;
|
||||
break;
|
||||
}
|
||||
|
||||
return newRoot;
|
||||
}
|
||||
|
||||
if (node == null) {
|
||||
return node;
|
||||
}
|
||||
|
||||
node.left = addOneRow(depth, val, node.left, currentDepth + 1, Side.Left);
|
||||
node.right = addOneRow(depth, val, node.right, currentDepth + 1, Side.Right);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
public TreeNode addOneRow(TreeNode root, int val, int depth) {
|
||||
return addOneRow(depth, val, root, 1, Side.Left);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue