# class Tree:# def __init__(self, val, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defsolve(self,root): count =0defdfs(root):if root: left =dfs(root.left) right =dfs(root.right)if root.val >= left and root.val >= right:nonlocal count count +=1return root.valreturnmax(left, right)else:return0dfs(root)return count
We use a post order DFS here. Post order means:
Left children
Visits right children
Visit current node
We use post-order traversal to visit subtrees recursively. By visiting each subtree, we solve the problem at that subtree and eventually solve the full problem.
We need to do this because of this part of the question:
all of its descendants.
Our algorithm will go down to these subtrees first:
And then these:
And finally this:
The answer increments by 1 whenever node.val == subtree_max.