Advertisement
kosievdmerwe

Untitled

Oct 23rd, 2021
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. #     def __init__(self, val=0, left=None, right=None):
  4. #         self.val = val
  5. #         self.left = left
  6. #         self.right = right
  7. class Solution:
  8.     def countNodes(self, root: Optional[TreeNode]) -> int:
  9.         if not root:
  10.             return 0
  11.        
  12.         def _left_height(node: Optional[TreeNode]) -> int:
  13.             ans = 0
  14.             while node:
  15.                 ans += 1
  16.                 node = node.left
  17.             return ans
  18.        
  19.         def _right_height(node: Optional[TreeNode]) -> int:
  20.             ans = 0
  21.             while node:
  22.                 ans += 1
  23.                 node = node.right
  24.             return ans
  25.        
  26.         def count_nodes(
  27.             node: Optional[TreeNode],
  28.             left_height: Optional[int],
  29.             right_height: Optional[int],
  30.         ) -> int:
  31.             if node is None:
  32.                 return 0
  33.            
  34.             if left_height is None:
  35.                 left_height = 1 + _left_height(node.left)
  36.             if right_height is None:
  37.                 right_height = 1 + _right_height(node.right)
  38.                
  39.             if left_height == right_height:
  40.                 return (2 ** left_height) - 1
  41.            
  42.             return (
  43.                 1
  44.                 + count_nodes(node.left, left_height - 1, None)
  45.                 + count_nodes(node.right, None, right_height - 1)
  46.             )
  47.        
  48.         return count_nodes(root, None, None)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement