Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 1448 · DFS Basics

Count Good Nodes in Binary Tree

LeetCode 1448 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Pass the path maximum down.

మధ్యస్థంTreeDepth-First SearchBreadth-First SearchBinary Tree
LeetCode లో తెరవండి ↗

నేను Count Good Nodes in Binary Tree (LeetCode 1448) ను ఇలా పరిష్కరించాను — DFS Basics ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

A node is good if no node on the path from the root is larger. Carry the largest value seen on the current path down the recursion and compare.

Approach

  1. 1

    dfs(node, max): None → 0.

  2. 2

    Count 1 if node.val ≥ max.

  3. 3

    Update max and add the counts from both children.

నేను ఎలా పరిష్కరించాను

DFS with path maxPythonO(n) time · O(h) space
class Solution:
    def goodNodes(self, root):
        def dfs(node, mx):
            if node is None:
                return 0
            res = 1 if node.val >= mx else 0
            mx = max(node.val, mx)
            res += dfs(node.left, mx)
            res += dfs(node.right, mx)
            return res
        return dfs(root, float("-inf"))
స్టెప్-త్రూ లోడ్ అవుతోంది…

Count Good Nodes in Binary Tree — తరచూ అడిగే ప్రశ్నలు

Count Good Nodes in Binary Tree వెనుక ఉన్న intuition ఏమిటి?

A node is good if no node on the path from the root is larger. Carry the largest value seen on the current path down the recursion and compare.

Count Good Nodes in Binary Tree (LeetCode 1448) ను ఎలా పరిష్కరించాలి?

1. dfs(node, max): None → 0. 2. Count 1 if node.val ≥ max. 3. Update max and add the counts from both children.

Count Good Nodes in Binary Tree యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(h). (Accepted approach: DFS with path max.)

Count Good Nodes in Binary Tree లో సాధారణ పొరపాట్లు ఏమిటి?

Use ≥ — equal values count as good.