[LeetCode] Count Complete Tree Nodes

아르당·2025년 10월 28일

LeetCode

목록 보기
53/68
post-thumbnail

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

Problem

완전 이진 트리 root가 주어졌을 때, 트리에 노드의 수를 반환해라.

Example

#1

Input: root = [1, 2, 3, 4, 5, 6]
Output: 6

#2
Input: root = []
Output: 0

#3
Input: root = [1]
Output: 1

Constraints

  • 트리에 노드의 수는 0에서 5* 10^4까지 범위 안에 있다.
  • 0 <= Node.val <= 5 * 10^4
  • 트리는 완전함이 보장된다.

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 int countNodes(TreeNode root) {
        if(root == null) return 0;

        return 1 + countNodes(root.left) + countNodes(root.right);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글