-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBSTDeadEnd.java
More file actions
37 lines (28 loc) · 1.01 KB
/
BSTDeadEnd.java
File metadata and controls
37 lines (28 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
package BinarySearchTrees;
import java.util.HashSet;
public class BSTDeadEnd {
static void findAllNodes(Node root, HashSet<Integer> allNodes) {
if (root == null) return;
allNodes.add(root.val);
findAllNodes(root.left, allNodes);
findAllNodes(root.right, allNodes);
}
static boolean check(Node root, HashSet<Integer> allNodes) {
if (root == null) return false;
if (root.left == null && root.right == null) {
int pre = root.val - 1;
int next = root.val + 1;
if (allNodes.contains(pre) && allNodes.contains(next)) {
return true;
}
}
return check(root.left, allNodes) || check(root.right, allNodes);
}
public static boolean isDeadEnd(Node root) {
if (root == null) return false;
HashSet<Integer> allNodes = new HashSet<>();
allNodes.add(0); // For nodes with values 1.
findAllNodes(root, allNodes);
return check(root, allNodes);
}
}