From c249f3a0f1aff16db83a07322e0c2ef481f466fb Mon Sep 17 00:00:00 2001 From: ArthurP Date: Thu, 11 Nov 2021 22:32:25 +0000 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200104.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6.md=20C?= =?UTF-8?q?=E8=AF=AD=E8=A8=80=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index e20f147f..1c94994f 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -582,6 +582,61 @@ var maxDepth = function(root) { }; ``` +## C +二叉树最大深度递归 +```c +int maxDepth(struct TreeNode* root){ + //若传入结点为NULL,返回0 + if(!root) + return 0; + + //求出左子树深度 + int left = maxDepth(root->left); + //求出右子树深度 + int right = maxDepth(root->right); + //求出左子树深度和右子树深度的较大值 + int max = left > right ? left : right; + //返回较大值+1(1为当前层数) + return max + 1; +} +``` +二叉树最大深度迭代 +```c +int maxDepth(struct TreeNode* root){ + //若传入根节点为NULL,返回0 + if(!root) + return 0; + + int depth = 0; + //开辟队列空间 + struct TreeNode** queue = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * 6000); + int queueFront = 0; + int queueEnd = 0; + + //将根结点入队 + queue[queueEnd++] = root; + + int queueSize; + //求出当前队列中元素个数 + while(queueSize = queueEnd - queueFront) { + int i; + //若当前队列中结点有左右子树,则将它们的左右子树入队 + for(i = 0; i < queueSize; i++) { + struct TreeNode* tempNode = queue[queueFront + i]; + if(tempNode->left) + queue[queueEnd++] = tempNode->left; + if(tempNode->right) + queue[queueEnd++] = tempNode->right; + } + //更新队头下标 + queueFront += queueSize; + //深度+1 + depth++; + } + return depth; +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321)