Count Good Nodes in a Binary Tree
Count the nodes that are at least as large as every node above them.
The problem
Implement Solution.goodNodes(root). root is the root TreeNode of a binary tree; each node has val, left and right. A node is good when no node on the path from the root down to it has a larger value. The root is always good, and a value equal to the largest one above it still counts. Return the number of good nodes as an int. An empty tree (root is None) has 0 good nodes. Trees are written in level order with None for a missing child. In [3, 1, 4, 3, None, 1, 5] the good nodes are the root 3, the 4, the 5, and the 3 under the 1, so the answer is 4. Constraints: the tree has 0 to 100,000 nodes with values from -10,000 to 10,000. Do not change the tree.
Starter code
class Solution:
def goodNodes(self, root):
passPublic examples
root = [3, 1, 4, 3, None, 1, 5]gives4root = [3, 2, None, 1]gives1root = [0, 0, 0]gives3
Solving it in the practice book needs an active paid plan.
Open it in the practice book