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 ```python
class solution: """
def maxdepth(self, root: 'node') -> int: # Definition for a Node.
st = [] class Node:
if root: def __init__(self, val=None, children=None):
st.append(root) self.val = val
depth = 0 self.children = children
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: class Solution:
node = st.pop() def maxDepth(self, root: 'Node') -> int:
depth -= 1 if not root:
result = max(result, depth) return 0
return result
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
``` ```