Skip to content

Commit 6bef886

Browse files
committed
Runtime: 73 ms (Top 66.36%) | Memory: 23.80 MB (Top 18.91%)
1 parent c9280e5 commit 6bef886

File tree

1 file changed

+18
-15
lines changed

1 file changed

+18
-15
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
1+
// Runtime: 73 ms (Top 66.36%) | Memory: 23.80 MB (Top 18.91%)
2+
13
class Solution:
2-
def countNodes(self, root: Optional[TreeNode]) -> int:
3-
def solve(_r):
4-
# base cond 1 when root is None
5-
if _r is None: return 0
6-
# base cond 2 when root is the leaf node
7-
if _r.left is None and _r.right is None:
8-
return 1
9-
# count of nodes in left subtree
10-
l = solve(_r.left)
11-
# count of nodes in right subtree
12-
r = solve(_r.right)
13-
# take the sum of left subtree / right subtree + root(1)
14-
return l + r + 1
15-
16-
return solve(root)
4+
# @param {TreeNode} root
5+
# @return {integer}
6+
def countNodes(self, root):
7+
if not root:
8+
return 0
9+
leftDepth = self.getDepth(root.left)
10+
rightDepth = self.getDepth(root.right)
11+
if leftDepth == rightDepth:
12+
return pow(2, leftDepth) + self.countNodes(root.right)
13+
else:
14+
return pow(2, rightDepth) + self.countNodes(root.left)
15+
16+
def getDepth(self, root):
17+
if not root:
18+
return 0
19+
return 1 + self.getDepth(root.left)

0 commit comments

Comments
 (0)