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.