题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是规定,一个二叉树节点,如果根节点到这个节点的路上没有比节点值更大的点,那么这个点就是好节点,求好节点数目。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def goodNodes(self, root: Optional[TreeNode]) -> int:
ans = 0
def dfs(root: Optional[TreeNode], cur_max: int):
if not root:
return
if root.val >= cur_max:
nonlocal ans
ans += 1
cur_max = max(cur_max, root.val)
dfs(root.left, cur_max)
dfs(root.right, cur_max)
dfs(root, root.val)
return ans