From 9356debd174b412729496b9ee254597967d551b2 Mon Sep 17 00:00:00 2001 From: Haoting <1165101405@qq.com> Date: Sat, 27 Apr 2024 17:08:54 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00104=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=20C?= =?UTF-8?q?=E8=AF=AD=E8=A8=80=E8=BF=AD=E4=BB=A3=E6=B3=95=E2=80=94=E2=80=94?= =?UTF-8?q?=E5=90=8E=E5=BA=8F=E9=81=8D=E5=8E=86=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 37 ++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 0f93cb0f..607e195b 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -829,7 +829,42 @@ int maxDepth(struct TreeNode* root){ return depth; } ``` - +二叉树最大深度迭代——后序遍历实现 +```c +int maxDepth(struct TreeNode *root) +{ + if(root == NULL) + return 0; + struct TreeNode *stack[10000] = {}; + int top = -1; + struct TreeNode *p = root, *r = NULL; // r指向上一个被访问的结点 + int depth = 0, maxDepth = -1; + while(p != NULL || top >= 0) + { + if(p != NULL) + { + stack[++top] = p; + depth++; + p = p->left; + } + else + { + p = stack[top]; + if(p->right != NULL && p->right != r) // 右子树未被访问 + p = p->right; + else + { + if(depth >= maxDepth) maxDepth = depth; + p = stack[top--]; + depth--; + r = p; + p = NULL; + } + } + } + return maxDepth; +} +``` ### Swift: 104.二叉树的最大深度