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

मी 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.