코딩테스트

[leetcode] 1448. Count Good Nodes in Binary Tree

nayoon 2024. 6. 14. 00:52

 

문제

 

/**
 * 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 static int cnt;
    public int goodNodes(TreeNode root) {
        cnt = 0;
        
        count(root, root.val);
        return cnt;
    }

    public void count(TreeNode node, int parent) {
        if (node == null) {
            return;
        }
        
        if (node.val >= parent) {
            cnt += 1;
            parent = node.val;
        }

        count(node.left, parent);
        count(node.right, parent);
    }
}