-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12_CountCompleteBinaryTree.py
More file actions
38 lines (32 loc) · 1.1 KB
/
12_CountCompleteBinaryTree.py
File metadata and controls
38 lines (32 loc) · 1.1 KB
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
# Question link - https://leetcode.com/problems/count-complete-tree-nodes/submissions/1745706208/?envType=study-plan-v2&envId=top-interview-150
# 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:
# Base case : as the height .
if root is None:
return 0
# height left subtree
lh = self.findHeightofLeftTree(root)
rh = self.fingHeightofrightTree(root)
if lh == rh:
return (1 << lh) - 1
else:
# Not equal at last level
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
def findHeightofLeftTree(self,node):
height = 0
while node:
height += 1
node = node.left
return height
def fingHeightofrightTree(self ,node):
height = 0
while node:
height += 1
node = node.right
return height