[LeetCode] Univalued Binary Tree

아르당·2일 전

LeetCode

목록 보기
209/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

이진 트리는 모든 노드가 같은 값을 가질 때 단일값 트리라고 한다.

이진 트리 root가 주어졌을 때, 해당 트리가 단일값 트리면 true, 그렇지 않다면 false를 반환해라.

Example

#1

Input: root = [1, 1, 1, 1, 1, null, 1]
Output: true

#2

Input: root = [2, 2, 2, 5, 2]
Output: false

Constraints

  • 트리에 있는 노드의 수는 [1, 100] 범위에 있다.
  • 0 <= Node.val < 100

Solved

/**
 * 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);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글