python实现二叉树的算法
时间: 2023-11-28 11:46:18 浏览: 83
以下是Python实现二叉树的算法:
1.定义二叉树节点类
```python
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
```
2.实现二叉树的遍历
- 前序遍历
```python
def preorderTraversal(root):
if not root:
return []
res = []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
```
- 中序遍历
```python
def inorderTraversal(root):
if not root:
return []
res = []
stack = []
while stack or root:
if root:
stack.append(root)
root = root.left
else:
node = stack.pop()
res.append(node.val)
root = node.right
return res
```
- 后序遍历
```python
def postorderTraversal(root):
if not root:
return []
res = []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return res[::-1]
```
- 层次遍历
```python
def levelOrder(root):
if not root:
return []
res = []
queue = [root]
while queue:
level = []
for i in range(len(queue)):
node = queue.pop(0)
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(level)
return res
```
阅读全文