Skip to content

Commit 6541ea8

Browse files
committed
count good nodes in binary tree
1 parent ff0295b commit 6541ea8

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

go/count-good-nodes-in-binary-tree.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package main
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* type TreeNode struct {
6+
* Val int
7+
* Left *TreeNode
8+
* Right *TreeNode
9+
* }
10+
*/
11+
func goodNodes(root *TreeNode) int {
12+
if root == nil {
13+
return 0
14+
}
15+
16+
sum := 1
17+
if root.Left != nil {
18+
sum = traverse(root.Left, root.Val) + sum
19+
}
20+
if root.Right != nil {
21+
sum = traverse(root.Right, root.Val) + sum
22+
}
23+
return sum
24+
}
25+
26+
func traverse(root *TreeNode, maxVal int) int {
27+
sum := 0
28+
if root.Val >= maxVal {
29+
sum++
30+
maxVal = root.Val
31+
}
32+
33+
if root.Left != nil {
34+
sum = traverse(root.Left, maxVal) + sum
35+
}
36+
if root.Right != nil {
37+
sum = traverse(root.Right, maxVal) + sum
38+
}
39+
return sum
40+
}

0 commit comments

Comments
 (0)