Advertisement
Guest User

Untitled

a guest
Nov 13th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1.     def countNodes(self, root):
  2.         """
  3.        :type root: TreeNode
  4.        :rtype: int
  5.        """
  6.         '''
  7.        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)
  8.        if lheight and rheight are same => return 2^height-1 (because that are number of nodes in a whole complete BT)
  9.        o/w count(left_sub_tree) and count(right_sub_tree) recursively
  10.        return LST_count + RST_count+1
  11.        '''
  12.         def count(root):
  13.             if root is None:
  14.                 return 0
  15.             cur_left, cur_right = root, root
  16.             lheight, rheight = 0, 0
  17.             while cur_left:
  18.                 cur_left=cur_left.left
  19.                 lheight+=1
  20.             while cur_right:
  21.                 cur_right=cur_right.right
  22.                 rheight+=1
  23.             if lheight==rheight:
  24.                 return 2**lheight-1
  25.             return count(root.left)+count(root.right)+1
  26.        
  27.         return count(root)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement