Leetcode 1448: Count Good Nodes in Binary Tree

grid47
grid47
Exploring patterns and algorithms
Jun 15, 2024 6 min read

Given the root of a binary tree, a node is considered ‘good’ if in the path from the root to that node, there are no nodes with a value greater than the node itself. Return the total number of good nodes in the tree.
Problem
Approach
Steps
Complexity
Input: The binary tree is represented by its root node. Each node contains a value and pointers to its left and right child nodes.
Example: Input: root = [4, 2, 7, 1, 3, 6, 9]
Constraints:
• The number of nodes in the tree is in the range [1, 10^5].
• Each node's value lies in the range [-10^4, 10^4].
Output: An integer representing the total count of good nodes in the tree.
Example: Output: 5
Constraints:
• The count must include the root node since it is always considered 'good'.
Goal: Count the number of nodes in the tree that are 'good' as per the defined criteria.
Steps:
• Traverse the tree using Depth-First Search (DFS).
• At each node, check if its value is greater than or equal to the maximum value encountered so far along the path from the root.
• If the node satisfies the condition, increment the count of good nodes.
• Update the maximum value encountered so far and recursively traverse the left and right subtrees.
Goal: Conditions to ensure correctness and efficiency of the solution.
Steps:
• The tree may have up to 10^5 nodes, so the algorithm should handle large inputs efficiently.
• Node values can be negative, zero, or positive.
Assumptions:
• The tree is non-empty and has at least one node (the root).
• Node values are integers.
Input: Input: root = [5, 3, 8, 2, 4, 7, 9]
Explanation: Output: 5. Nodes 5, 8, 9, 3, and 4 are good. The path from the root to each of these nodes does not contain a value greater than the node.

Input: Input: root = [10, 9, 11]
Explanation: Output: 3. All nodes are good as there are no values greater than themselves in their respective paths.

Input: Input: root = [6, 2, 8, 1, 4]
Explanation: Output: 4. Nodes 6, 8, 4, and 1 are good. Node 2 is not good as 6 is greater than 2 in the path.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus