/**
* 给你一棵根为 root 的二叉树,请你返回二叉树中好节点的数目。
*
* 「好节点」X 定义为:从根到该节点 X 所经过的节点中,没有任何节点的值大于 X 的值。
*
* 参考链接: https://leetcode.cn/problems/count-good-nodes-in-binary-tree/?envType=study-plan-v2&envId=leetcode-75
*/
public class GoodNodes {
/**
* 深度优先搜索
*/
int count = 0
public int goodNodes(TreeNode root) {
if (root==null) {
return 0
}
dfs(root, root.val)
return count
}
public void dfs(TreeNode root, int max) {
int val = root.val
if (val >= max) {
count++
}
max = Math.max(max, val)
if (root.left != null) {
dfs(root.left, max)
}
if (root.right != null) {
dfs(root.right, max)
}
}
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
}
}
}