본문 바로가기
LeetCode/2020 LeetCoding Challenge

LeetCode. Count Complete Tree Nodes

by 벤진[Benzene] 2020. 6. 24.

Problem:

Given a complete binary tree, count the number of nodes.

Note:

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, 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.

 

Example:

-Summary-

Solve by recursion

1. if the root exists, we add 1 then move to the left and right subtree.

2. if the root is None, return 0.

 

# 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: TreeNode) -> int:
        return 1+self.countNodes(root.left)+self.countNodes(root.right) if root else 0

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

'LeetCode > 2020 LeetCoding Challenge' 카테고리의 다른 글

LeetCode. Unique Paths  (0) 2020.06.30
LeetCode. Sum Root to Leaf Numbers  (0) 2020.06.27
LeetCode.Single Number II  (0) 2020.06.23
LeetCode.H-Index II  (0) 2020.06.19
LeetCode.Surrounded Regions  (0) 2020.06.18

댓글