LeetCode 1448: Count Good Nodes in Binary Tree

Day 35 of #75DaysOfLeetCode 🚀 LeetCode 1448 — Count Good Nodes in Binary Tree Just solved an interesting tree problem that really strengthens DFS concepts! 🌳 👉 Problem Insight: A node in a binary tree is considered “good” if no node on the path from root to it has a value greater than it. 💡 Approach: Traverse the tree using DFS Keep track of the maximum value seen so far If current node ≥ max_so_far → it's a good node Update max and continue traversal 🧠 This problem is a great example of: ✔️ Tree traversal (DFS) ✔️ Passing state in recursion ✔️ Decision making at each node ⏱ Complexity: Time: O(n) Space: O(h) 💻 Java Code: class Solution { public int goodNodes(TreeNode root) { return dfs(root, root.val); } private int dfs(TreeNode node, int maxSoFar) { if (node == null) return 0; int count = 0; if (node.val >= maxSoFar) { count = 1; maxSoFar = node.val; } count += dfs(node.left, maxSoFar); count += dfs(node.right, maxSoFar); return count; } } 🔥 Key Takeaway: Always think about what information needs to be carried along the recursion path — here, it's the maximum value so far. #LeetCode #DataStructures #BinaryTree #DFS #Java #CodingInterview #100DaysOfCode

  • text

To view or add a comment, sign in

Explore content categories