Count Good Nodes in Binary Tree — LeetCode 1448 Python Solution

MediumTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#1448
Reading time
4 min

The problem

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

Input
root = [3,1,4,3,null,1,5]
Output
4
Explanation
Nodes in blue are good.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        def dfs(root: TreeNode, mx: int):
            if root is None:
                return
            nonlocal ans
            if mx <= root.val:
                ans += 1
                mx = root.val
            dfs(root.left, mx)
            dfs(root.right, mx)

        ans = 0
        dfs(root, -1000000)
        return ans

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1448. Count Good Nodes in Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and LeetCode 75.

Frequently asked questions

How hard is LeetCode 1448. Count Good Nodes in Binary Tree?
LeetCode 1448. Count Good Nodes in Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 1448. Count Good Nodes in Binary Tree?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 1448. Count Good Nodes in Binary Tree?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 1448. Count Good Nodes in Binary Tree cover?
LeetCode 1448. Count Good Nodes in Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview