leet-code/count-good-nodes-in-binary-.../sol.go

45 lines
712 B
Go
Raw Normal View History

2022-09-01 18:10:51 +00:00
/*
* @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
}