imashutosh51

Sum Tree

Jul 31st, 2022 (edited)
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.60 KB | None | 0 0
  1. def fun(self, node, ans):
  2.     if not node:
  3.         return 0
  4.     # leaf node
  5.     if not node.left and not node.right:
  6.         return node.data
  7.    
  8.     # subtree sums
  9.     left_sum = self.fun(node.left, ans)
  10.     right_sum = self.fun(node.right, ans)
  11.    
  12.     # Sum Tree condition
  13.     if left_sum + right_sum != node.data:
  14.         ans[0] = False
  15.    
  16.     # total subtree sum
  17.     return left_sum + right_sum + node.data
  18.        
  19. class Solution:
  20.     def is_sum_tree(self, node):
  21.         if not node:
  22.             return True
  23.         ans = [True]
  24.         self.fun(node, ans)
  25.         return ans[0]
Advertisement
Add Comment
Please, Sign In to add comment