添加0104二叉树的最大深度 C语言迭代法——后序遍历实现

This commit is contained in:
Haoting
2024-04-27 17:08:54 +08:00
parent 672374d4ea
commit 9356debd17

View File

@ -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.二叉树的最大深度