-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRightSiblingTree.java
42 lines (38 loc) · 992 Bytes
/
RightSiblingTree.java
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
import java.util.*;
class Program {
// O(n) time | O(d) space
public static BinaryTree rightSiblingTree(BinaryTree root) {
// Write your code here.
convertToRightSiblingTree(root, null, false);
return root;
}
private static void convertToRightSiblingTree(BinaryTree node, BinaryTree parent, boolean isLeftChild) {
if (node == null) {
return;
}
BinaryTree left = node.left;
BinaryTree right = node.right;
convertToRightSiblingTree(left, node, true);
if (parent == null) {
node.right = null;
} else if (isLeftChild) {
node.right = parent.right;
} else {
if (parent.right == null) {
node.right = null;
} else {
node.right = parent.right.left;
}
}
convertToRightSiblingTree(right, node, false);
}
// This is the class of the input root. Do not edit it.
static class BinaryTree {
int value;
BinaryTree left = null;
BinaryTree right = null;
public BinaryTree(int value) {
this.value = value;
}
}
}