LeetCode 1448 Count Good Nodes in Binary Tree (Python)

Posted by 小明MaxMing on May 16, 2020

题目

Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.

Return the number of good nodes in the binary tree.

解题思路

DFS,每次将路径上的最大值传给下一层,并把左右子树的结果以及当前节点是否符合条件求出总和,返回给上一层

代码

class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        def dfs(root, max_val):
            res = int(root.val >= max_val)
            if root.left:
                res += dfs(root.left, max(max_val, root.val))
            if root.right:
                res += dfs(root.right, max(max_val, root.val))
            return res
        
        return dfs(root, -10000)

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅