mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加0104二叉树的最大深度 C语言迭代法——后序遍历实现
This commit is contained in:
@ -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.二叉树的最大深度
|
||||
|
Reference in New Issue
Block a user