Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 673ce85

Browse files
feature: add go solution for leetcode 0968
1 parent 1fed77c commit 673ce85

File tree

2 files changed

+80
-3
lines changed

2 files changed

+80
-3
lines changed

‎solution/0900-0999/0968.Binary Tree Cameras/README.md‎

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,47 @@
6060

6161
```
6262

63-
### **...**
64-
```
65-
63+
### **Go**
64+
```go
65+
/**
66+
* Definition for a binary tree node.
67+
* type TreeNode struct {
68+
* Val int
69+
* Left *TreeNode
70+
* Right *TreeNode
71+
* }
72+
*/
73+
74+
var res int
75+
func minCameraCover(root *TreeNode) int {
76+
res = 0
77+
//三种状态,后序遍历
78+
if root == nil {
79+
return 0
80+
}
81+
if dfs(root) == 0 {
82+
res++
83+
}
84+
return res
85+
}
86+
//0:待覆盖,1:已覆盖,2:安装
87+
88+
func dfs(root *TreeNode) int {
89+
if root == nil {
90+
return 1
91+
}
92+
l := dfs(root.Left)
93+
r := dfs(root.Right)
94+
//左右子节点存在待覆盖状态,当前节点要安装
95+
if l == 0 || r == 0 {
96+
res++
97+
return 2
98+
} else if l == 1 && r == 1 { //左右节点均为已覆盖,则当前节点为待覆盖
99+
return 0
100+
}
101+
//除上述情况外,左右子节点中至少有一个安装了监控,当前节点为已覆盖
102+
return 1
103+
}
66104
```
67105

68106
<!-- tabs:end -->
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* type TreeNode struct {
4+
* Val int
5+
* Left *TreeNode
6+
* Right *TreeNode
7+
* }
8+
*/
9+
10+
var res int
11+
func minCameraCover(root *TreeNode) int {
12+
res = 0
13+
//三种状态,后序遍历
14+
if root == nil {
15+
return 0
16+
}
17+
if dfs(root) == 0 {
18+
res++
19+
}
20+
return res
21+
}
22+
//0:待覆盖,1:已覆盖,2:安装
23+
24+
func dfs(root *TreeNode) int {
25+
if root == nil {
26+
return 1
27+
}
28+
l := dfs(root.Left)
29+
r := dfs(root.Right)
30+
//左右子节点存在待覆盖状态,当前节点要安装
31+
if l == 0 || r == 0 {
32+
res++
33+
return 2
34+
} else if l == 1 && r == 1 { //左右节点均为已覆盖,则当前节点为待覆盖
35+
return 0
36+
}
37+
//除上述情况外,左右子节点中至少有一个安装了监控,当前节点为已覆盖
38+
return 1
39+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /