bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 1448. Count Good Nodes in Binary Tree

1448. Count Good Nodes in Binary Tree

Leetcode Solutions

Depth First Search, Recursion

  1. Define a helper function dfs that takes a node and the maximum value seen so far as arguments.
  2. If the node is null, return 0 (base case).
  3. Initialize a variable count to 0.
  4. If the node's value is greater than or equal to the maximum value seen so far, increment count.
  5. Recursively call dfs for the left child, passing the greater of the node's value or the current maximum as the new maximum.
  6. Recursively call dfs for the right child, similarly updating the maximum.
  7. Return count plus the counts from the left and right subtree calls.
  8. Call dfs with the root node and the smallest possible integer value (representing the maximum value seen so far) and return the result.
UML Thumbnail

Breadth First Search

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...