Skip to content

Commit 8b52b2f

Browse files
authored
1448. Count Good Nodes in Binary Tree
1 parent 1b61427 commit 8b52b2f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

1448.CountGoodNodesinBinaryTree.kt

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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

Comments
 (0)