All problems

Problem 157

Count Good Nodes in Binary Tree

Medium · 20 pts · Tree, Depth-First Search, Binary Tree

Problem

A node X in a binary tree is good if no node on the path from the root down to X has a value greater than X. The root is always good. Count the good nodes in the given tree. Do a depth-first search that passes down the largest value seen so far on the current path. A node is good when its value is at least that maximum; then continue into its children with the updated maximum.

Input

First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses).

Output

Print the number of good nodes.

Constraints

1 <= number of nodes <= 100000; -10000 <= value <= 10000

Example input

7
3 1 4 3 null 1 5

Example output

4

Explanation

The root 3 is good. Its left child 1 is not (3 > 1), but 1's child 3 is good (the path 3, 1, 3 has no value above 3). The right child 4 is good, its child 1 is not, and its child 5 is good. That is 4 good nodes: 3, 3, 4 and 5.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Binary Tree Zigzag Level Order Next: Binary Tree Maximum Path Sum