[LeetCode] Count Good Nodes in Binary Tree

1448. Count Good Nodes in Binary Tree

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int search(TreeNode* node, int X) {
int res = node->val >= X;
if(node->left != nullptr) {
res += search(node->left, max(X, node->val));
}
if(node->right != nullptr) {
res += search(node->right, max(X, node->val));
}

return res;
}
public:
int goodNodes(TreeNode* root) {
return search(root, root->val);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int goodNodes(TreeNode* root, int X = INT_MIN) {
return root == nullptr ? 0 :
(root->val >= X) + goodNodes(root->left, max(X, root->val)) + goodNodes(root->right, max(X, root->val));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/10/PS/LeetCode/count-good-nodes-in-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.