ZhongKuo0228 / study

0 stars 0 forks source link

1448. Count Good Nodes in Binary Tree #92

Open fockspaces opened 7 months ago

fockspaces commented 7 months ago
  1. DFS 把 path 上最大值傳下去
  2. 遇到空節點 return 0
  3. 一路判斷,最後即能得到 good nodes counts
# 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: TreeNode) -> int:
        def DFS(root, cur_max):
            if not root:
                return 0
            cur_max = max(cur_max, root.val)
            return DFS(root.left, cur_max) + DFS(root.right, cur_max) + (root.val >= cur_max)
        return DFS(root, root.val)