|
16 | 16 | class Solution {
|
17 | 17 | public int goodNodes(TreeNode root) {
|
18 | 18 | int[] count = {0};
|
19 |
| - helper(root, root.val, count); |
| 19 | + getGoodNodesCountRecursive(root, Integer.MIN_VALUE, count); |
20 | 20 | return count[0];
|
21 | 21 | }
|
22 | 22 |
|
23 |
| - private void helper(TreeNode root, int currMax, int[] count) { |
| 23 | + private void getGoodNodesCountRecursive(TreeNode root, int currMax, int[] count) { |
24 | 24 | if (root == null) {
|
25 | 25 | return;
|
26 | 26 | }
|
27 | 27 | if (root.val >= currMax) {
|
28 | 28 | count[0]++;
|
29 | 29 | }
|
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 | + } |
32 | 64 | }
|
33 | 65 | }
|
0 commit comments