@@ -577,6 +577,91 @@ object Solution {
577
577
result
578
578
}
579
579
}
580
+ ```
581
+ ### Rust
582
+ ``` Rust
583
+ /// 版本一
584
+ impl Solution {
585
+ pub fn min_camera_cover (root : Option <Rc <RefCell <TreeNode >>>) -> i32 {
586
+ let mut res = 0 ;
587
+ if Self :: traversal (& root , & mut res ) == 0 {
588
+ res += 1 ;
589
+ }
590
+ res
591
+ }
592
+
593
+ pub fn traversal (cur : & Option <Rc <RefCell <TreeNode >>>, ans : & mut i32 ) -> i32 {
594
+ // 0 未覆盖 1 节点已设置摄像头 2 节点已覆盖
595
+ if let Some (node ) = cur {
596
+ let node = node . borrow ();
597
+
598
+ let left = Self :: traversal (& node . left, ans );
599
+ let right = Self :: traversal (& node . right, ans );
600
+
601
+ // 左右节点都被覆盖
602
+ if left == 2 && right == 2 {
603
+ return 0 ; // 无覆盖
604
+ }
605
+
606
+ // left == 0 right == 0 左右无覆盖
607
+ // left == 0 right == 1 左节点无覆盖 右节点有摄像头
608
+ // left == 1 right == 0 左节点有摄像头 左节点无覆盖
609
+ // left == 0 right == 2 左节点无覆盖 右节点有覆盖
610
+ // left == 2 right == 0 左节点有覆盖 右节点无覆盖
611
+ if left == 0 || right == 0 {
612
+ * ans += 1 ;
613
+ return 1 ;
614
+ }
615
+
616
+ // left == 1 right == 1 左节点有摄像头 右节点有摄像头
617
+ // left == 1 right == 2 左节点有摄像头 右节点覆盖
618
+ // left == 2 right == 1 左节点覆盖 右节点有摄像头
619
+ if left == 1 || right == 1 {
620
+ return 2 ; // 已覆盖
621
+ }
622
+ } else {
623
+ return 2 ;
624
+ }
625
+ - 1
626
+ }
627
+ }
628
+
629
+ /// 版本二
630
+ enum NodeState {
631
+ NoCover = 0 ,
632
+ Camera = 1 ,
633
+ Covered = 2 ,
634
+ }
635
+
636
+ impl Solution {
637
+ pub fn min_camera_cover (root : Option <Rc <RefCell <TreeNode >>>) -> i32 {
638
+ let mut res = 0 ;
639
+ let state = Self :: traversal (& root , & mut res );
640
+ match state {
641
+ NodeState :: NoCover => res + 1 ,
642
+ _ => res ,
643
+ }
644
+ }
645
+
646
+ pub fn traversal (cur : & Option <Rc <RefCell <TreeNode >>>, ans : & mut i32 ) -> NodeState {
647
+ if let Some (node ) = cur {
648
+ let node = node . borrow ();
649
+ let left_state = Self :: traversal (& node . left, ans );
650
+ let right_state = Self :: traversal (& node . right, ans );
651
+ match (left_state , right_state ) {
652
+ (NodeState :: NoCover , _ ) | (_ , NodeState :: NoCover ) => {
653
+ * ans += 1 ;
654
+ NodeState :: Camera
655
+ }
656
+ (NodeState :: Camera , _ ) | (_ , NodeState :: Camera ) => NodeState :: Covered ,
657
+ (_ , _ ) => NodeState :: NoCover ,
658
+ }
659
+ } else {
660
+ NodeState :: Covered
661
+ }
662
+ }
663
+ }
664
+
580
665
```
581
666
582
667
<p align =" center " >
0 commit comments