【LetMeFly】1448. Count the number of good nodes in the binary tree
Leetcode question link: https://leetcode.cn/problems/count-good-nodes-in-binary-tree/
Given a root
binary tree with root , please return the number of good nodes in the binary tree.
"Good node" X is defined as: among the nodes passing from the root to the node X, no node's value is greater than the value of X.
Example 1:
Input: root = [3,1,4,3,null,1,5] Output: 4 Explanation: The blue node in the graph is a good node. The root node (3) is always a good node. Node 4 -> (3,4) is the maximum value in the path. Node 5 -> (3,4,5) is the maximum value in the path. Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:
Input: root = [3,3,null,4,2] Output: 3 Explanation: Node 2 -> (3, 3, 2) is not a good node because "3" is larger than it.
Example 3:
Input: root = [1] Output: 1 Explanation: The root node is a good node.
hint:
- The range of the number of nodes in a binary tree is
[1, 10^5]
. - The range of each node's weight is
[-10^4, 10^4]
.
Method 1: Depth First Search (DFS)
goodNodes
Add a parameter with a default value of "infinitesimal" to the current parentMax
function to record the maximum value among the ancestor nodes of the current node.
If root
empty, returns 0;
Otherwise, update parentMax
to the maximum value of the ancestor node and the current node, and recurse the left and right children.
- Time complexity O ( n ) O(n)O ( n ) , of whichnnn is the maximum depth of the binary tree
- Space complexity O ( n ) O(n)O ( n )
AC code
C++
class Solution {
public:
int goodNodes(TreeNode* root, int parentMax=-100000) {
if (!root) {
return 0;
}
int nowMax = max(parentMax, root->val);
return (root->val >= parentMax) + goodNodes(root->left, nowMax) + goodNodes(root->right, nowMax);
}
};
Python
# from typing import Optional
# # 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: Optional[TreeNode], parentMax=-100000) -> int:
if not root:
return 0
nowMax = max(root.val, parentMax)
return (root.val >= parentMax) + self.goodNodes(root.left, nowMax) + self.goodNodes(root.right, nowMax)
The article is published simultaneously on CSDN. It is not easy to be original. Please attach the link to the original article after reprinting with the author's consent ~
Tisfy: https://letmefly.blog.csdn.net/article/details/132491754