-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCount Complete Tree Nodes.py
44 lines (33 loc) · 1.04 KB
/
Count Complete Tree Nodes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
Time: O(n)
Memory: O(log(n))
"""
def countNodes(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
class Solution:
"""
Time: O(log^2(n))
Memory: O(log(n))
"""
def countNodes(self, root: Optional[TreeNode], nodes: int = 0) -> int:
if root is None:
return nodes
if root.left is None and root.right is None:
return nodes + 1
if self.height(root.left) == self.height(root.right):
return self.countNodes(root.right, 2 * nodes + 2)
return self.countNodes(root.left, 2 * nodes + 1)
@classmethod
def height(cls, root: Optional[TreeNode]) -> int:
if root is None:
return 0
return 1 + cls.height(root.left)