-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCountGoodNodes.java
40 lines (39 loc) · 963 Bytes
/
CountGoodNodes.java
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
/*https://leetcode.com/problems/count-good-nodes-in-binary-tree/*/
class Solution {
int count;
Stack<Integer> stack;
public int goodNodes(TreeNode root) {
count = 1;
stack = new Stack<Integer>();
traverse(root);
return count;
}
void traverse(TreeNode root)
{
if (root == null) return;
if (stack.isEmpty())
{
stack.push(root.val);
traverse(root.left);
traverse(root.right);
stack.pop();
}
else
{
if (root.val >= stack.peek())
++count;
if (stack.peek() < root.val)
{
stack.push(root.val);
traverse(root.left);
traverse(root.right);
stack.pop();
}
else
{
traverse(root.left);
traverse(root.right);
}
}
}
}