Skip to content

Commit 5d3baf8

Browse files
Create 1361-validate-binary-tree-nodes.java
1 parent 2746c43 commit 5d3baf8

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/* BFS
2+
--------------------------------
3+
Time Complexity: O(n)
4+
Space Complexity: O(n)
5+
------------------------------*/
6+
7+
class Solution {
8+
public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
9+
int root = findRoot(n, leftChild, rightChild);
10+
if(root == -1)
11+
return false;
12+
13+
Set<Integer> visited = new HashSet<>();
14+
Queue<Integer> q = new LinkedList<>();
15+
16+
q.add(root);
17+
visited.add(root);
18+
19+
while(!q.isEmpty()){
20+
int node = q.poll();
21+
int[] childerns = {leftChild[node], rightChild[node]};
22+
23+
for(int c: childerns){
24+
if(c == -1)
25+
continue;
26+
if(visited.contains(c))
27+
return false;
28+
q.add(c);
29+
visited.add(c);
30+
}
31+
}
32+
return visited.size() == n;
33+
}
34+
private int findRoot(int n, int[] leftChild, int[] rightChild){
35+
Set<Integer> set = new HashSet<>();
36+
for(int lc: leftChild)
37+
set.add(lc);
38+
for(int rc: rightChild)
39+
set.add(rc);
40+
41+
for(int i = 0; i < n; i++){
42+
if(!set.contains(i))
43+
return i;
44+
}
45+
return -1;
46+
}
47+
}

0 commit comments

Comments
 (0)