|
| 1 | +/** |
| 2 | + * Example: |
| 3 | + * var ti = TreeNode(5) |
| 4 | + * var v = ti.`val` |
| 5 | + * Definition for a binary tree node. |
| 6 | + * class TreeNode(var `val`: Int) { |
| 7 | + * var left: TreeNode? = null |
| 8 | + * var right: TreeNode? = null |
| 9 | + * } |
| 10 | + */ |
| 11 | +//https://leetcode.com/problems/count-good-nodes-in-binary-tree/description |
| 12 | +class Solution { |
| 13 | + var count = 0 |
| 14 | + fun goodNodes(root: TreeNode?): Int { |
| 15 | + goodNodeCount(root, Int.MIN_VALUE) |
| 16 | + return count |
| 17 | + } |
| 18 | + |
| 19 | + fun goodNodeCount(node: TreeNode?, maxParent: Int){ |
| 20 | + if(node == null) return |
| 21 | + |
| 22 | + val isGoodNode = node.`val` >= maxParent |
| 23 | + if(isGoodNode){ |
| 24 | + count++ |
| 25 | + } |
| 26 | + |
| 27 | + val currentMax = maxOf(maxParent, node.`val`) |
| 28 | + goodNodeCount(node.left, currentMax) |
| 29 | + goodNodeCount(node.right, currentMax) |
| 30 | + } |
| 31 | +} |
0 commit comments