1448. Count Good Nodes in Binary Tree
Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Example 2:
Example 3:
- The number of nodes in the binary tree is in the range [1, 10^5].
- Each node's value is between [-10^4, 10^4].
Constraints:
Notes
Intuition
Keep track of the largest node seen in the path.
Implementation
Since we are going down the path, we use DFS. Define our recursive function to the node and a max value parameter. Base case is if the root is null, return. Otherwise, check if max value is less than or equal to the current node's value (i.e. the node is larger or equal to the largest value seen before this in its path), if true, increment the good nodes counter. Call the DFS function on left and right side taking the max of the current max value and the node's value.
- Time: O(n), each node is processed once
- Space: O(n), call stack