解题思路
递归三部曲:
- 传递参数:当前的子节点node,当前树节点中的最大值
- 结束条件:树遍历结束 node == nil
- 单层遍历流程: 如果当前节点的值大于或等于最大值,则result累加1并且替换最大值
复杂度分析
由于本题使用先序遍历对二叉树中每一个节点遍历一次,所以时间复杂度为O(n)
示例代码
func goodNodes(root *TreeNode) int {
result := 0
maxValue := math.MinInt64
var orderFunc func(node *TreeNode, maxValue int)
orderFunc = func(node *TreeNode, maxValue int) {
if node == nil {
return
}
if node.Val >= maxValue {
result++
maxValue = node.Val
}
orderFunc(node.Left, maxValue)
orderFunc(node.Right, maxValue)
}
orderFunc(root, maxValue)
return result
}