From 3107ba208c7f0872018053e3dab987c7eb3dd057 Mon Sep 17 00:00:00 2001 From: ArthurP Date: Sat, 28 Aug 2021 20:47:20 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200968.=E7=9B=91?= =?UTF-8?q?=E6=8E=A7=E4=BA=8C=E5=8F=89=E6=A0=91.md=20C=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0968.监控二叉树.md | 39 ++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/0968.监控二叉树.md b/problems/0968.监控二叉树.md index c715279a..737e92a0 100644 --- a/problems/0968.监控二叉树.md +++ b/problems/0968.监控二叉树.md @@ -406,6 +406,45 @@ var minCameraCover = function(root) { }; ``` +C: +```c +/* +**函数后序遍历二叉树。判断一个结点状态时,根据其左右孩子结点的状态进行判断 +**状态:0为没有被摄像头覆盖到。1为此结点处应设置摄像头。2为此结点已被摄像头覆盖 +*/ +int traversal(struct TreeNode* node, int* ans) { + //递归结束条件:传入结点为NULL,假设此结点能被摄像头覆盖。这样方便与对叶子结点的判断,将叶子结点设为0 + if(!node) + return 2; + //后序遍历二叉树,记录左右孩子的状态。根据左右孩子状态更新结点自身状态 + int left = traversal(node->left, ans); + int right = traversal(node->right, ans); + + //若左右孩子都可以被摄像头覆盖,将父亲结点状态设为0 + if(left == 2 && right == 2) { + return 0; + } + //若左右孩子有一个结点状态为没有被覆盖(0),则将父亲结点状态设置为摄像头 + if(left == 0 || right == 0) { + (*ans)++; + return 1; + } + //若左右孩子有一个为摄像头,证明父亲结点可以被覆盖。将父亲结点状态变为2 + if(left == 1 || right == 1) + return 2; + //逻辑不会走到-1,语句不会执行 + return -1; +} + +int minCameraCover(struct TreeNode* root){ + int ans = 0; + + //在对整个二叉树遍历后。头结点可能未被覆盖,这时候如果函数返回值为0,证明头结点未被覆盖。说明头结点也需要添置摄像头,ans++ + if(traversal(root, &ans) == 0) + ans++; + return ans; +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) From d7cadd601f1cd665780108bcdc5974480c7d7907 Mon Sep 17 00:00:00 2001 From: ArthurP Date: Sat, 28 Aug 2021 20:51:26 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200122.=E4=B9=B0?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?II.md=20C=E8=AF=AD=E8=A8=80=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0122.买卖股票的最佳时机II.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index 29aa5b83..bd837eea 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -229,6 +229,21 @@ var maxProfit = function(prices) { }; ``` +C: +```c +int maxProfit(int* prices, int pricesSize){ + int result = 0; + int i; + //从第二个元素开始遍历数组,与之前的元素进行比较 + for(i = 1; i < pricesSize; ++i) { + //若该元素比前面元素大,则说明有利润。代表买入 + if(prices[i] > prices[i-1]) + result+= prices[i]-prices[i-1]; + } + return result; +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321)