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() class Solution:
if node != none: def maxDepth(self, root: 'Node') -> int:
st.append(node) #中 if not root:
st.append(none) return 0
depth += 1
for i in range(len(node.children)): #处理孩子 max_depth = 0
if node.children[i]:
st.append(node.children[i]) stack = [(root, 1)]
else: while stack:
node = st.pop() node, depth = stack.pop()
depth -= 1 max_depth = max(max_depth, depth)
result = max(result, depth) for child in node.children:
return result stack.append((child, depth + 1))
return max_depth
``` ```