count-good-nodes-in-binary-tree

This commit is contained in:
Gleb Koval 2022-09-01 18:10:51 +00:00
parent 5edf7fa141
commit dd88ef2c57
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
1 changed files with 44 additions and 0 deletions

View File

@ -0,0 +1,44 @@
/*
* @lc app=leetcode id=1448 lang=golang
*
* [1448] Count Good Nodes in Binary Tree
*/
package main
// @lc code=start
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
import "math"
func goodNodes(root *TreeNode) int {
return subGoodNodes(root, math.MinInt)
}
func subGoodNodes(root *TreeNode, previousMax int) int {
if root == nil {
return 0
}
sum := 0
max := previousMax
if root.Val >= previousMax {
sum = 1
max = root.Val
}
sum += subGoodNodes(root.Left, max)
sum += subGoodNodes(root.Right, max)
return sum
}
// @lc code=end
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}