728x90
반응형
https://github.com/ROUTINE-STUDY/Algorithm
알고리즘 스터디를 진행하고 있습니다. 😊
초보들로 구성되어있으며, 열심히 풀어보고 풀이 방식을 공유하고 피드백을 해주는 스터디입니다.
참여 문의는 댓글 혹은 GitHub 주소를 참고해주세요.
문제 출처 : https://leetcode.com/problems/univalued-binary-tree/
Univalued Binary Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제 설명
주어진 트리의 모든 노드의 값이 일치하면 true, 아니면 false를 반환하세요.
풀이 방법
값이 다른 노드가 나오면 false 처리, 이외는 true 처리
탐색 순서 및 방향은 결과에 영향을 주지 않기 때문에 BFS 안쪽 for문 삭제
내 코드(JAVA)
public class Solution {
public boolean isUnivalTree(TreeNode root) {
Queue<TreeNode> q = new ArrayDeque<>();
int value = 0;
q.add(root);
value = root.val;
while(!q.isEmpty()) {
TreeNode node = q.poll();
if(value != root.val) return false;
if(node.left != null) q.add(node.left);
if(node.right != null) q.add(node.right);
}
return true;
}
}
BFS 까먹지 않게 꾸준히 풀어봅시다.
728x90
반응형
'알고리즘' 카테고리의 다른 글
[프로그래머스/JAVA] 부족한 금액 계산하기 (0) | 2021.09.08 |
---|---|
[LeetCode/JAVA] 1684. Count the Number of Consistent Strings (0) | 2021.09.04 |
[LeetCode/JAVA] 993. Cousins in Binary Tree (0) | 2021.08.31 |
[프로그래머스/JAVA] 숫자 문자열과 영단어 (0) | 2021.08.29 |
[프로그래머스/JAVA] 직업군 추천하기 (0) | 2021.08.28 |
댓글