-
Notifications
You must be signed in to change notification settings - Fork 22
/
PrintAllNodesThatDontHaveSibling.java
51 lines (43 loc) · 1.35 KB
/
PrintAllNodesThatDontHaveSibling.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
43
44
45
46
47
48
49
50
51
package com.company.amazon;
import com.company.amazon.BinaryTree.Node;
import static com.company.amazon.BinaryTree.isLeafNode;
public class PrintAllNodesThatDontHaveSibling {
public static void main(String[] args) {
Node root = new Node(10);
root.left = new Node(2);
root.left.right = new Node(4);
root.right = new Node(3);
root.right.left = new Node(5);
root.right.left.left = new Node(6);
printNodes(root);
}
public static boolean isLeafNode(Node root) {
return root.left == null && root.right == null;
}
public static void printNodes(Node root) {
if (root == null) {
return;
}
if (!isLeafNode(root)) {
int nodeChild = ifNodeHasOneChild(root);
if (nodeChild != 0) {
if (nodeChild == 1) {
System.out.println(root.right.data);
} else {
System.out.println(root.left.data);
}
}
}
printNodes(root.left);
printNodes(root.right);
}
public static int ifNodeHasOneChild(Node node) {
if (node.left != null && node.right != null) {
return 0;
} else if (node.left != null && node.right == null) {
return -1;
} else {
return 1;
}
}
}