diff --git a/count-good-nodes-in-binary-tree/sol.go b/count-good-nodes-in-binary-tree/sol.go new file mode 100644 index 0000000..ddddbc0 --- /dev/null +++ b/count-good-nodes-in-binary-tree/sol.go @@ -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 +}