例子:
想到二叉树就想到递归,通过只考虑某一个节点的状态,并记录沿途的最大值,来判断即可。
代码如下:
class Solution {
int result = 0;
public int goodNodes(TreeNode root) {
if(root==null) return 0;
MaxGoodNodes(root,Integer.MIN_VALUE);
return result;
}
public void MaxGoodNodes(TreeNode root,int num){
if(root==null) return;
if(root.val>=num){
result++;
num = root.val;
}
MaxGoodNodes(root.left, num);
MaxGoodNodes(root.right,num);
}
}