150强访谈中等

计算二叉树中的好节点数

“计算二叉树中的好节点”问题的详细指南和 Python 实现。

问题陈述

中等

给定一个二叉树根,如果从根到 X 的路径中不存在值大于 X 的节点,则树中的节点 X 被命名为良好。

返回二叉树中好节点的数量。

该树被表示为一个级别顺序列表。实现函数 goodNodes(root: list) -> int

约束条件
  • The number of nodes in the binary tree is in the range [1, 100000]
  • -10000 <= Node.val <= 10000

示例

Example 1
Input
[3,1,4,3,None,1,5]
Output
4
Explanation

Root 3 is always good. Node 4 (3<=4, good). Node 3 under node 1 (3<=3, good). Node 5 (3<=4<=5, good). Node 1 is not good (3>1). Node 1 under 4 is not good (4>1). Total: 4 good nodes.

Example 2
Input
[3,3,None,4,2]
Output
3
Explanation

Root 3 is good. Node 3 (left child, 3<=3, good). Node 4 (3<=3<=4, good). Node 2 is not good (3>2). Total: 3.

Example 3
Input
[1]
Output
1
Explanation

The root is always a good node.

Need a Hint?
考虑使用树特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。