↓Skip to main content
  1. LeetCode/

LeetCode 1448: Count Good Nodes in Binary Tree

·1 min· ·
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-29

  • Submissions: Runtime Error ×2 → Accepted

Approach
#

A good node has nothing larger on its path from the root. Pass the path maximum down (Tree Template 1); count a node whose value is >= it, then recurse with the updated maximum.

My Attempts
#

The first two versions read an attribute of None and used an undefined variable; the third passed.

Solution
#

class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        def dfs(node, mx):
            if not node:
                return 0
            good = node.val >= mx
            mx = max(mx, node.val)
            return good + dfs(node.left, mx) + dfs(node.right, mx)
        return dfs(root, root.val)

Complexity
#

Time O(n), space O(h).

Mistakes to Avoid
#

  • Use >=; equal to the maximum counts (the root always does).

Interview Explanation
#

A DFS passes the path maximum down; a node at least that large is good, and recursion continues with the updated maximum. Time O(n).

Related

LeetCode 199: Binary Tree Right Side View
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 199 note: in a level-order traversal, each level’s rightmost node is what you see from the right
LeetCode 102: Binary Tree Level Order Traversal
·1 min
LeetCode Medium Tree Breadth-First-Search Binary-Tree
LeetCode 102 note: BFS one whole level at a time, building the next level from the current one; an empty tree returns an empty list
LeetCode 230: Kth Smallest Element in a BST
·1 min
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 230 note: a BST’s in-order traversal is ascending, so stop an iterative in-order walk at the k-th node
LeetCode 98: Validate Binary Search Tree
·2 mins
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 98 note: every node has a valid range (low, high); going left the upper bound becomes the node and going right the lower bound does; comparing parent and child is not enough
LeetCode 965: Univalued Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 965 note: every value must equal the root’s; compare values while recursing, not the booleans the recursion returns
LeetCode 993: Cousins in Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 993 note: cousins share a depth but not a parent; record x’s and y’s depth and parent during DFS and compare