엔지니어 게시판
LeetCode 솔루션 분류

[11/15] 222. Count Complete Tree Nodes

컨텐츠 정보

본문

222. Count Complete Tree Nodes
Medium
6649375Add to ListShare

Given the root of a complete binary tree, return the number of the nodes in the tree.

According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Design an algorithm that runs in less than O(n) time complexity.

 

Example 1:

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

Example 2:

Input: root = []
Output: 0

Example 3:

Input: root = [1]
Output: 1

 

Constraints:

  • The number of nodes in the tree is in the range [0, 5 * 104].
  • 0 <= Node.val <= 5 * 104
  • The tree is guaranteed to be complete.
Accepted
502,754
Submissions
846,550
태그 ,

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 193 ms, faster than 33.94% of Python3 online submissions for Count Complete Tree Nodes.
Memory Usage: 21.5 MB, less than 46.74% of Python3 online submissions for Count Complete Tree Nodes.
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root: return 0
        
        l_depth = self.count_depth(root.left)
        r_depth = self.count_depth(root.right)
    
        if l_depth == r_depth:
            return pow(2, l_depth) + self.countNodes(root.right)
        else:
            return pow(2, r_depth) + self.countNodes(root.left)
    
    
    def count_depth(self, node):
        if not node: return 0
        return 1 + self.count_depth(node.left)
전체 405 / 5 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 613 명
  • 오늘 방문자 6,854 명
  • 어제 방문자 7,431 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,542 명
알림 0