MCPcopy Create free account
hub / github.com/ROUTINE-STUDY/Algorithm / Sanghoo

Class Sanghoo

LeetCode/BFS/993. Cousins in Binary Tree/Sanghoo.java:8–50  ·  view source on GitHub ↗

https://leetcode.com/problems/cousins-in-binary-tree/

Source from the content-addressed store, hash-verified

6 * https://leetcode.com/problems/cousins-in-binary-tree/
7 */
8public class Sanghoo {
9
10 // Set의 특징을 이용한 풀이(중복을 허용하지 않음)
11 public boolean isCousins(TreeNode root, int x, int y) {
12 Queue<TreeNode> q = new LinkedList<>();
13 Set<TreeNode> setParent = new HashSet<>();
14 Set<Integer> setDepth = new HashSet<>();
15 int depth = 0;
16
17 q.add(root);
18
19 while(!q.isEmpty()) {
20 int size = q.size();
21
22 for(int i=0; i<size; i++) {
23 TreeNode node = q.poll();
24
25 if(node.left != null) {
26 if(node.left.val == x || node.left.val == y) {
27 setParent.add(node);
28 setDepth.add(depth);
29 }
30 q.add(node.left);
31 }
32
33 if(node.right != null) {
34 if(node.right.val == x || node.right.val == y) {
35 setParent.add(node);
36 setDepth.add(depth);
37 }
38 q.add(node.right);
39 }
40 }
41 depth++;
42 }
43
44 // 부모가 달라야한다, 깊이는 같아야한다
45 if(setParent.size() < 2 || setDepth.size() > 1) return false;
46
47 return true;
48 }
49
50}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected