Merge pull request #1818 from MIracleyin/master

添加 968 监控二叉树 Rust 版本
This commit is contained in:
程序员Carl
2022-12-30 10:32:42 +08:00
committed by GitHub

View File

@ -577,6 +577,91 @@ object Solution {
result
}
}
```
### Rust
```Rust
/// 版本一
impl Solution {
pub fn min_camera_cover(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut res = 0;
if Self::traversal(&root, &mut res) == 0 {
res += 1;
}
res
}
pub fn traversal(cur: &Option<Rc<RefCell<TreeNode>>>, ans: &mut i32) -> i32 {
// 0 未覆盖 1 节点已设置摄像头 2 节点已覆盖
if let Some(node) = cur {
let node = node.borrow();
let left = Self::traversal(&node.left, ans);
let right = Self::traversal(&node.right, ans);
// 左右节点都被覆盖
if left == 2 && right == 2 {
return 0; // 无覆盖
}
// left == 0 right == 0 左右无覆盖
// left == 0 right == 1 左节点无覆盖 右节点有摄像头
// left == 1 right == 0 左节点有摄像头 左节点无覆盖
// left == 0 right == 2 左节点无覆盖 右节点有覆盖
// left == 2 right == 0 左节点有覆盖 右节点无覆盖
if left == 0 || right == 0 {
*ans += 1;
return 1;
}
// left == 1 right == 1 左节点有摄像头 右节点有摄像头
// left == 1 right == 2 左节点有摄像头 右节点覆盖
// left == 2 right == 1 左节点覆盖 右节点有摄像头
if left == 1 || right == 1 {
return 2; // 已覆盖
}
} else {
return 2;
}
-1
}
}
/// 版本二
enum NodeState {
NoCover = 0,
Camera = 1,
Covered = 2,
}
impl Solution {
pub fn min_camera_cover(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut res = 0;
let state = Self::traversal(&root, &mut res);
match state {
NodeState::NoCover => res + 1,
_ => res,
}
}
pub fn traversal(cur: &Option<Rc<RefCell<TreeNode>>>, ans: &mut i32) -> NodeState {
if let Some(node) = cur {
let node = node.borrow();
let left_state = Self::traversal(&node.left, ans);
let right_state = Self::traversal(&node.right, ans);
match (left_state, right_state) {
(NodeState::NoCover, _) | (_, NodeState::NoCover) => {
*ans += 1;
NodeState::Camera
}
(NodeState::Camera, _) | (_, NodeState::Camera) => NodeState::Covered,
(_, _) => NodeState::NoCover,
}
} else {
NodeState::Covered
}
}
}
```
<p align="center">