This is my current favorite channel! Love your explanations :) I was able to code it myself after listening to your explanation!❤ class Solution: def averageOfSubtree(self, root: TreeNode) -> int: # do a postorder count = [0] def dfs(node): if not node: return (0, 0) #sum, no.of nodes val_l, count_l = dfs(node.left) val_r, count_r = dfs(node.right) total_val = node.val + val_l + val_r total_count = 1+count_l+count_r avg = total_val // total_count if node.val == avg: count[0]+=1 return (total_val, total_count) dfs(root) return count[0]
Yea it's a strange one, But once you realise you can return whatever you want from it then it allows you to get creative and solve a lot of these more easily
This is my current favorite channel! Love your explanations :) I was able to code it myself after listening to your explanation!❤
class Solution:
def averageOfSubtree(self, root: TreeNode) -> int:
# do a postorder
count = [0]
def dfs(node):
if not node: return (0, 0) #sum, no.of nodes
val_l, count_l = dfs(node.left)
val_r, count_r = dfs(node.right)
total_val = node.val + val_l + val_r
total_count = 1+count_l+count_r
avg = total_val // total_count
if node.val == avg:
count[0]+=1
return (total_val, total_count)
dfs(root)
return count[0]
Amazing solution. Wish you the best!
why self for variable types?
I bombed this question because i never seen recursion returning tuple pattern before
Yea it's a strange one, But once you realise you can return whatever you want from it then it allows you to get creative and solve a lot of these more easily