Update 0104.二叉树的最大深度.md

This commit is contained in:
jianghongcheng
2023-05-03 22:04:25 -05:00
committed by GitHub
parent be27cc547d
commit 1b1b51750d

View File

@ -494,30 +494,32 @@ class Solution:
```
使用栈来模拟后序遍历依然可以
使用栈
```python
class solution:
def maxdepth(self, root: 'node') -> int:
st = []
if root:
st.append(root)
depth = 0
result = 0
while st:
node = st.pop()
if node != none:
st.append(node) #中
st.append(none)
depth += 1
for i in range(len(node.children)): #处理孩子
if node.children[i]:
st.append(node.children[i])
else:
node = st.pop()
depth -= 1
result = max(result, depth)
return result
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
max_depth = 0
stack = [(root, 1)]
while stack:
node, depth = stack.pop()
max_depth = max(max_depth, depth)
for child in node.children:
stack.append((child, depth + 1))
return max_depth
```