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.