1448. Count Good Nodes in Binary Tree - Medium

前往題目

想法

  • 搜尋的時候維護最大值

思路

難得自己寫出來DFS

  1. DFS
  2. 搜尋時維護最大值

Code

class Solution {
    private int res; // Result
    public int goodNodes(TreeNode root) {
        res = 0;
        // Start DFS
        dfs(root, Integer.MIN_VALUE);
        return res;
    }

    private void dfs(TreeNode node, int max) {
        // Reached the leaf
        if (node == null) return;

        // Decide if it's a good node
        if (node.val >= max) {
            ++res;
            max = node.val;
        }

        // Keep searching
        dfs(node.left, max);
        dfs(node.right, max);

        return;
    }
}

1448. Count Good Nodes in Binary Tree - Medium
https://f88083.github.io/2024/02/07/1448-Count-Good-Nodes-in-Binary-Tree-Medium/
作者
Simon Lai
發布於
2024年2月7日
許可協議