Count Good Nodes in Binary Tree
LeetCode 1448 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Pass the path maximum down.
ನಾನು 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
dfs(node, max): None → 0.
- 2
Count 1 if node.val ≥ max.
- 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.