Skip to content

Commit 259ec48

Browse files
authored
Added both recursive and non-recursive implementation
1 parent 95c5bf3 commit 259ec48

File tree

1 file changed

+36
-4
lines changed

1 file changed

+36
-4
lines changed

Medium/Count Good Nodes in Binary Tree.java

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,50 @@
1616
class Solution {
1717
public int goodNodes(TreeNode root) {
1818
int[] count = {0};
19-
helper(root, root.val, count);
19+
getGoodNodesCountRecursive(root, Integer.MIN_VALUE, count);
2020
return count[0];
2121
}
2222

23-
private void helper(TreeNode root, int currMax, int[] count) {
23+
private void getGoodNodesCountRecursive(TreeNode root, int currMax, int[] count) {
2424
if (root == null) {
2525
return;
2626
}
2727
if (root.val >= currMax) {
2828
count[0]++;
2929
}
30-
helper(root.left, Math.max(currMax, root.val), count);
31-
helper(root.right, Math.max(currMax, root.val), count);
30+
getGoodNodesCountRecursive(root.left, Math.max(currMax, root.val), count);
31+
getGoodNodesCountRecursive(root.right, Math.max(currMax, root.val), count);
32+
}
33+
34+
private int getGoodNodesCountNonRecursive(TreeNode root) {
35+
if (root == null) {
36+
return 0;
37+
}
38+
int count = 0;
39+
Queue<TreePair> queue = new LinkedList<>();
40+
queue.add(new TreePair(root, Integer.MIN_VALUE));
41+
while (!queue.isEmpty()) {
42+
TreePair removed = queue.remove();
43+
if (removed.node.val >= removed.currMax) {
44+
count++;
45+
}
46+
if (removed.node.left != null) {
47+
queue.add(new TreePair(removed.node.left, Math.max(removed.node.val, removed.currMax)));
48+
}
49+
if (removed.node.right != null) {
50+
queue.add(new TreePair(removed.node.right, Math.max(removed.node.val, removed.currMax)));
51+
}
52+
}
53+
return count;
54+
}
55+
56+
class TreePair {
57+
int currMax;
58+
TreeNode node;
59+
60+
public TreePair(TreeNode node, int currMax) {
61+
this.currMax = currMax;
62+
this.node = node;
63+
}
3264
}
3365
}

0 commit comments

Comments
 (0)