Skip to content

Latest commit

 

History

History
59 lines (49 loc) · 1.56 KB

_1448. Count Good Nodes in Binary Tree.md

File metadata and controls

59 lines (49 loc) · 1.56 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : July 04, 2024

Last updated : July 04, 2024


Related Topics : Tree, Depth-First Search, Breadth-First Search, Binary Tree

Acceptance Rate : 73.34 %


Solutions

Java

/**
 * 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) {
        return goodNodesHelper(root, Integer.MIN_VALUE);
    }
    private int goodNodesHelper(TreeNode curr, int maxPrevious) {
        int output = (curr.val >= maxPrevious) ? 1 : 0;
        int maxx = Integer.max(curr.val, maxPrevious);
        if (curr.left != null) {
            output += goodNodesHelper(curr.left, maxx);
        }
        if (curr.right != null) {
            output += goodNodesHelper(curr.right, maxx);
        }
        return output;
    }
}