1448. Count Good Nodes in Binary Tree

1448. Count Good Nodes in Binary Tree

Question

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.

Solution

DFS搜索,每次传入当前分支的最大值。
如果当前值大于等于最大值,则count+1。

Code

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
29
30
31
32
33
34
/**
* 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 count;
public int goodNodes(TreeNode root) {
count = 0;
dfs(root, Integer.MIN_VALUE);
return count;
}

private void dfs(TreeNode root, int max){
if(root == null) return;
if(root.val >= max){
count++;
max = root.val;
}

dfs(root.left, max);
dfs(root.right, max);
}
}
Author

Xander

Posted on

2022-09-01

Updated on

2022-09-01

Licensed under

Comments