Skip to content

Commit 9356deb

Browse files
committed
添加0104二叉树的最大深度 C语言迭代法——后序遍历实现
1 parent 672374d commit 9356deb

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

problems/0104.二叉树的最大深度.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -829,7 +829,42 @@ int maxDepth(struct TreeNode* root){
829829
return depth;
830830
}
831831
```
832-
832+
二叉树最大深度迭代——后序遍历实现
833+
```c
834+
int maxDepth(struct TreeNode *root)
835+
{
836+
if(root == NULL)
837+
return 0;
838+
struct TreeNode *stack[10000] = {};
839+
int top = -1;
840+
struct TreeNode *p = root, *r = NULL; // r指向上一个被访问的结点
841+
int depth = 0, maxDepth = -1;
842+
while(p != NULL || top >= 0)
843+
{
844+
if(p != NULL)
845+
{
846+
stack[++top] = p;
847+
depth++;
848+
p = p->left;
849+
}
850+
else
851+
{
852+
p = stack[top];
853+
if(p->right != NULL && p->right != r) // 右子树未被访问
854+
p = p->right;
855+
else
856+
{
857+
if(depth >= maxDepth) maxDepth = depth;
858+
p = stack[top--];
859+
depth--;
860+
r = p;
861+
p = NULL;
862+
}
863+
}
864+
}
865+
return maxDepth;
866+
}
867+
```
833868
### Swift:
834869
835870
104.二叉树的最大深度

0 commit comments

Comments
 (0)