Open songyy5517 opened 4 months ago
Approach: DFS
num
to record the number of good nodes;Complexity Analysis
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int num = 0;
public int goodNodes(TreeNode root) {
if (root == null)
return 0;
dfs(root, root.val);
return num;
}
void dfs(TreeNode root, int max){
if (root == null)
return ;
if (root.val >= max)
num ++;
dfs(root.left, Math.max(root.val, max));
dfs(root.right, Math.max(root.val, max));
}
}
2024/6/1
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.
Example 1:
Example 2:
Example 3:
Intuition This problem is to find out all the nodes that is the maximum on the path from the root node to itself. A simple idea is to travarse all the nodes with DFS, and then for each node determine whether it is a good node. The key here is how to determine whether a node is good or not. We can keep a variable to record the maximum node value on the path from root to the current node. If the current node is greater than the maximum node value, then it is a good node, and we update the maximum node value.