Skip to content

Commit 0ef6bfa

Browse files
authored
Create 1361_Validate_Binary_Tree_Nodes.java
1 parent 47c9b9a commit 0ef6bfa

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// id: 1361
2+
// Name: Validate Binary Tree Nodes
3+
// link: https://leetcode.com/problems/validate-binary-tree-nodes/
4+
// Difficulty: Medium
5+
6+
class Solution {
7+
public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
8+
boolean [] visited;
9+
// for improvement, find root and apply bfs on root node only.
10+
for (int root = 0; root < n; root++) {
11+
visited = new boolean[n];
12+
// perform traversal from this node
13+
// bfs
14+
Queue<Integer> q = new LinkedList<Integer>();
15+
q.offer(root);
16+
17+
int visitedCount = 0;
18+
19+
boolean flag = true; // false, if cycle
20+
while (!q.isEmpty()) {
21+
int e = q.poll();
22+
visitedCount++;
23+
24+
if (visited[e]) {
25+
flag = false;
26+
break;
27+
}
28+
29+
visited[e] = true;
30+
31+
if (leftChild[e] != -1) q.offer(leftChild[e]);
32+
if (rightChild[e] != -1) q.offer(rightChild[e]);
33+
}
34+
// check if all are visited
35+
if (flag && visitedCount == n) {
36+
return true;
37+
}
38+
}
39+
return false;
40+
}
41+
}

0 commit comments

Comments
 (0)