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
|
```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
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user