File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -406,6 +406,45 @@ var minCameraCover = function(root) {
406
406
};
407
407
```
408
408
409
+ C:
410
+ ``` c
411
+ /*
412
+ **函数后序遍历二叉树。判断一个结点状态时,根据其左右孩子结点的状态进行判断
413
+ **状态:0为没有被摄像头覆盖到。1为此结点处应设置摄像头。2为此结点已被摄像头覆盖
414
+ */
415
+ int traversal (struct TreeNode* node, int* ans) {
416
+ //递归结束条件:传入结点为NULL,假设此结点能被摄像头覆盖。这样方便与对叶子结点的判断,将叶子结点设为0
417
+ if(!node)
418
+ return 2;
419
+ //后序遍历二叉树,记录左右孩子的状态。根据左右孩子状态更新结点自身状态
420
+ int left = traversal(node->left, ans);
421
+ int right = traversal(node->right, ans);
422
+
423
+ //若左右孩子都可以被摄像头覆盖,将父亲结点状态设为0
424
+ if(left == 2 && right == 2) {
425
+ return 0;
426
+ }
427
+ //若左右孩子有一个结点状态为没有被覆盖(0),则将父亲结点状态设置为摄像头
428
+ if(left == 0 || right == 0) {
429
+ (*ans)++;
430
+ return 1;
431
+ }
432
+ //若左右孩子有一个为摄像头,证明父亲结点可以被覆盖。将父亲结点状态变为2
433
+ if(left == 1 || right == 1)
434
+ return 2;
435
+ //逻辑不会走到-1,语句不会执行
436
+ return -1;
437
+ }
438
+
439
+ int minCameraCover(struct TreeNode* root){
440
+ int ans = 0;
441
+
442
+ //在对整个二叉树遍历后。头结点可能未被覆盖,这时候如果函数返回值为0,证明头结点未被覆盖。说明头结点也需要添置摄像头,ans++
443
+ if(traversal(root, &ans) == 0)
444
+ ans++;
445
+ return ans;
446
+ }
447
+ ```
409
448
410
449
-----------------------
411
450
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
You can’t perform that action at this time.
0 commit comments