mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-13 22:35:09 +08:00
Update 0104.二叉树的最大深度.md
This commit is contained in:
@ -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])
|
||||
"""
|
||||
# Definition for a Node.
|
||||
class Node:
|
||||
def __init__(self, val=None, children=None):
|
||||
self.val = val
|
||||
self.children = children
|
||||
"""
|
||||
|
||||
else:
|
||||
node = st.pop()
|
||||
depth -= 1
|
||||
result = max(result, depth)
|
||||
return result
|
||||
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
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user