Featured image of post 1448. 统计二叉树中好节点的数目

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

题目描述

给你一棵根为 root 的二叉树,请你返回二叉树中好节点的数目。

「好节点」X 定义为:从根到该节点 X 所经过的节点中,没有任何节点的值大于 X 的值。

示例 1:

  • 输入:root = [3,1,4,3,null,1,5]
  • 输出:4
  • 解释:图中蓝色节点为好节点。 根节点 (3) 永远是个好节点。 节点 4 -> (3,4) 是路径中的最大值。 节点 5 -> (3,4,5) 是路径中的最大值。 节点 3 -> (3,1,3) 是路径中的最大值。

示例 2:

  • 输入:root = [3,3,null,4,2]
  • 输出:3
  • 解释:节点 2 -> (3, 3, 2) 不是好节点,因为 “3” 比它大。

示例 3:

  • 输入:root = [1]
  • 输出:1
  • 解释:根节点是好节点。

提示:

  • 二叉树中节点数目范围是 [1, 10^5] 。
  • 每个节点权值的范围是 [-10^4, 10^4] 。

解法一:DFS

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func goodNodes(root *TreeNode) int {
    maxVal := math.MinInt32
    ans := 0
    var dfs func(root *TreeNode)
    dfs = func(root *TreeNode) {
        if root == nil {
            return
        }
        raw := maxVal
        defer func() { maxVal = raw }()
        if root.Val >= maxVal {
            ans++
            maxVal = root.Val
        }
        dfs(root.Left)
        dfs(root.Right)
    }
    dfs(root)
    return ans
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/08/25 08:18:52
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计