문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
이진 트리는 모든 노드가 같은 값을 가질 때 단일값 트리라고 한다.
이진 트리 root가 주어졌을 때, 해당 트리가 단일값 트리면 true, 그렇지 않다면 false를 반환해라.
#1
Input: root = [1, 1, 1, 1, 1, null, 1]
Output: true
#2
Input: root = [2, 2, 2, 5, 2]
Output: false
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isUnivalTree(TreeNode root) {
if(root == null){
return true;
}
if(root.left != null && root.left.val != root.val){
return false;
}
if(root.right != null && root.right.val != root.val){
return false;
}
return isUnivalTree(root.left) && isUnivalTree(root.right);
}
}