-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1448CountGoodNodesInBinaryTree.java
More file actions
56 lines (53 loc) · 1.59 KB
/
1448CountGoodNodesInBinaryTree.java
File metadata and controls
56 lines (53 loc) · 1.59 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//https://leetcode.com/problems/count-good-nodes-in-binary-tree/
/**
* 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 {
public int goodNodes(TreeNode root) {
//return dfs(root, root.val);
return bfs(root);
}
int bfs(TreeNode root) {
int sum = 0;
Queue<Pair<TreeNode, Integer>> queue = new LinkedList();
queue.add(new Pair<>(root, root.val));
while(!queue.isEmpty()) {
Pair<TreeNode, Integer> node = queue.remove();
if(node.getKey().val >= node.getValue()) {
sum += 1;
}
if(node.getKey().left != null) {
queue.add(new Pair<>(node.getKey().left, Math.max(node.getKey().left.val, node.getValue())));
}
if(node.getKey().right != null) {
queue.add(new Pair<>(node.getKey().right, Math.max(node.getKey().right.val, node.getValue())));
}
}
return sum;
}
int dfs(TreeNode root, int maxValue) {
if(root == null) {
return 0;
}
int sum = 0;
if(root.val >= maxValue) {
sum += 1;
maxValue = root.val;
}
sum += dfs(root.left, maxValue);
sum += dfs(root.right, maxValue);
return sum;
}
}