1448. Count Good Nodes in Binary Tree ¶ Time: $O(n)$ Space: $O(h)$ C++Java 1 2 3 4 5 6 7 8 9 10 11class Solution { public: int goodNodes(TreeNode* root, int mx = INT_MIN) { if (root == nullptr) return 0; const int newMax = max(mx, root->val); return (root->val >= mx) + // goodNodes(root->left, newMax) + // goodNodes(root->right, newMax); } }; 1 2 3 4 5 6 7 8 9 10 11 12 13class Solution { public int goodNodes(TreeNode root) { return goodNodes(root, Integer.MIN_VALUE); } private int goodNodes(TreeNode root, int mx) { if (root == null) return 0; final int newMax = Math.max(mx, root.val); return (root.val >= mx ? 1 : 0) + goodNodes(root.left, newMax) + goodNodes(root.right, newMax); } }