1448. Count Good Nodes in Binary Tree
🔗 Source
Approach
Recursion, using variable max to log the previous maximum value and compare max with current root value.
Complexity
- Time complexity: \(O(N)\)
 
- Space complexity: \(O(1)\)
 
Code
 | /**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int goodNodes(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int max= root.val;
        return 1 + helper(root.left, max) + helper(root.right, max);
    }
    public int helper(TreeNode root, int max) {
        if (root == null) {
            return 0;
        }
        if (max > root.val) {
            return helper(root.left, max) + helper(root.right, max);
        }
        max = Math.max(max, root.val);
        return 1 + helper(root.left, max) + helper(root.right, max);
    }
}
  |