LeetCode 솔루션 분류
[11/15] 222. Count Complete Tree Nodes
본문
222. Count Complete Tree Nodes
Medium
6649375Add to ListShareGiven 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.
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)