Leetcode 1448. 统计二叉树中好节点的数目

160 阅读1分钟

题目连接

解题思路

递归三部曲:

  1. 传递参数:当前的子节点node,当前树节点中的最大值
  2. 结束条件:树遍历结束 node == nil
  3. 单层遍历流程: 如果当前节点的值大于或等于最大值,则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
}