Skip to content

Commit 36a9939

Browse files
committed
968.监控二叉树,递归
1 parent 8065c2e commit 36a9939

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@
174174
739. 每日温度
175175
867. 转置矩阵
176176
901. 股票价格跨度
177+
968. 监控二叉树
177178
1020. 飞地的数量
178179
1035. 不相交的线
179180
1081. 不同字符的最小子序列

leetcode_Java/DoneType.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
589. N叉树的前序遍历(递归,迭代)
4141
617. 合并二叉树(递归,迭代)
4242
662. 二叉树最大宽度(递归,迭代)
43-
43+
968. 监控二叉树(递归)
4444

4545
二、回溯
4646
17. 电话号码的字母组合

leetcode_Java/Solution0968.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// 968. 监控二叉树
2+
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* public class TreeNode {
7+
* int val;
8+
* TreeNode left;
9+
* TreeNode right;
10+
* TreeNode() {}
11+
* TreeNode(int val) { this.val = val; }
12+
* TreeNode(int val, TreeNode left, TreeNode right) {
13+
* this.val = val;
14+
* this.left = left;
15+
* this.right = right;
16+
* }
17+
* }
18+
*/
19+
20+
21+
/*
22+
递归
23+
1、方法功能:入参是一个节点,返回该节点的监控状态
24+
0:该节点无覆盖 1:该节点有摄像头 2:该节点有覆盖
25+
2、终止条件:节点为空时,表示有覆盖,返回2
26+
3、一个节点处理过程和返回结果:节点不为空,表示无覆盖,返回0
27+
4、递归调用:左右节点同样需要获取监控状态,因此调用同样的方法递归处理,获取结果
28+
5、递归顺序:后序遍历,自底向上进行推导,因为尽量让叶子节点的父节点安装摄像头,这样摄像头的数量才是最少的
29+
6、使用递归调用结果和返回结果:
30+
1)左右节点其中一个无覆盖,那么当前节点需要安装摄像头,用于覆盖子节点,返回1
31+
2)左右节点其中一个有摄像头,那么当前节点有覆盖,返回2
32+
3)左右节点都有覆盖,那么当前节点无覆盖,交给当前节点的父节点处理,返回0
33+
4)根节点无覆盖,根节点没有父节点了,要自己处理,所以要安装摄像头
34+
*/
35+
class Solution {
36+
private int res = 0;
37+
38+
public int minCameraCover(TreeNode root) {
39+
return dfs(root) == 0 ? res + 1 : res;
40+
}
41+
42+
private int dfs(TreeNode root) {
43+
if (root == null) {
44+
return 2;
45+
}
46+
int left = dfs(root.left);
47+
int right = dfs(root.right);
48+
if (left == 0 || right == 0) {
49+
res++;
50+
return 1;
51+
}
52+
if (left == 1 || right == 1) {
53+
return 2;
54+
}
55+
return 0;
56+
}
57+
}

0 commit comments

Comments
 (0)