python中序遍历二叉树
时间: 2023-12-28 18:24:52 浏览: 88
以下是Python中序遍历二叉树的两种实现方法:
1. 递归实现:
```python
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def inorder(root):
if not root:
return
inorder(root.left)
res.append(root.val)
inorder(root.right)
inorder(root)
return res
```
2. 显式栈实现:
```python
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
stack = []
curr = root
while curr or stack:
while curr:
stack.append(curr)
curr = curr.left
curr = stack.pop()
res.append(curr.val)
curr = curr.right
return res
```
阅读全文