Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c8972d3

Browse files
author
侯利朋
committed
.\1145.binary-tree-coloring-game ok
1 parent f2e7610 commit c8972d3

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

1145.binary-tree-coloring-game.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
* @lc app=leetcode id=1145 lang=golang
3+
*
4+
* [1145] Binary Tree Coloring Game
5+
*/
6+
/**
7+
* Definition for a binary tree node.
8+
* type TreeNode struct {
9+
* Val int
10+
* Left *TreeNode
11+
* Right *TreeNode
12+
* }
13+
*/
14+
/**
15+
* Definition for a binary tree node.
16+
* type TreeNode struct {
17+
* Val int
18+
* Left *TreeNode
19+
* Right *TreeNode
20+
* }
21+
*/
22+
// 0 ms
23+
// 二手着色的最佳位置是 x的父节点,左,右子节点中节点数最多的那个
24+
func btreeGameWinningMove(root *TreeNode, n int, x int) bool {
25+
// find x
26+
nodeX := findnode(root, x)
27+
lNodes := nodes(nodeX.Left)
28+
rNodes := nodes(nodeX.Right)
29+
pNodes := n - lNodes - rNodes - 1
30+
return max3(lNodes, rNodes, pNodes) > n/2
31+
}
32+
33+
// TODO find 和 计算节点个数,两个函数可以合并
34+
func findnode(root *TreeNode, x int) *TreeNode {
35+
if root == nil {
36+
return nil
37+
}
38+
if root.Val == x {
39+
return root
40+
}
41+
if node := findnode(root.Left, x); node != nil {
42+
return node
43+
}
44+
return findnode(root.Right, x)
45+
}
46+
47+
// 返回root为根的树的节点个数
48+
func nodes(root *TreeNode) int {
49+
if root == nil {
50+
return 0
51+
}
52+
return 1 + nodes(root.Left) + nodes(root.Right)
53+
}
54+
55+
func max3(a, b, c int) int {
56+
if a >= b && a >= c {
57+
return a
58+
} else if b >= a && b >= c {
59+
return b
60+
}
61+
return c
62+
}

0 commit comments

Comments
 (0)