Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def countNodes(self, root):
- """
- :type root: TreeNode
- :rtype: int
- """
- '''
- if the complete binary tree has all the nodes then it's leftmost node height(lheight) will be same as right most node height (rheight)
- if lheight and rheight are same => return 2^height-1 (because that are number of nodes in a whole complete BT)
- o/w count(left_sub_tree) and count(right_sub_tree) recursively
- return LST_count + RST_count+1
- '''
- def count(root):
- if root is None:
- return 0
- cur_left, cur_right = root, root
- lheight, rheight = 0, 0
- while cur_left:
- cur_left=cur_left.left
- lheight+=1
- while cur_right:
- cur_right=cur_right.right
- rheight+=1
- if lheight==rheight:
- return 2**lheight-1
- return count(root.left)+count(root.right)+1
- return count(root)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement