实现一个二叉树的二叉链表的创建(递归、非递归均可),并实现二叉树的先序、中序和后序遍历(要求递归算法和非递归算法都要实现)和层次遍历的代码
时间: 2023-11-28 08:47:15 浏览: 87
编写采用二叉链表形式存储的二叉树的创建、先序、中序、后序和按层遍历的算法
5星 · 资源好评率100%
二叉树的二叉链表的创建(递归):
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def create_tree(arr: List[int], index: int) -> TreeNode:
if index >= len(arr) or arr[index] is None:
return None
root = TreeNode(arr[index])
root.left = create_tree(arr, 2 * index + 1)
root.right = create_tree(arr, 2 * index + 2)
return root
```
二叉树的先序遍历(递归):
```python
def pre_order_recursive(root: TreeNode):
if not root:
return
print(root.val, end=' ')
pre_order_recursive(root.left)
pre_order_recursive(root.right)
```
二叉树的先序遍历(非递归):
```python
def pre_order_iterative(root: TreeNode):
if not root:
return
stack = [root]
while stack:
node = stack.pop()
print(node.val, end=' ')
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
```
二叉树的中序遍历(递归):
```python
def in_order_recursive(root: TreeNode):
if not root:
return
in_order_recursive(root.left)
print(root.val, end=' ')
in_order_recursive(root.right)
```
二叉树的中序遍历(非递归):
```python
def in_order_iterative(root: TreeNode):
if not root:
return
stack = []
node = root
while stack or node:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
print(node.val, end=' ')
node = node.right
```
二叉树的后序遍历(递归):
```python
def post_order_recursive(root: TreeNode):
if not root:
return
post_order_recursive(root.left)
post_order_recursive(root.right)
print(root.val, end=' ')
```
二叉树的后序遍历(非递归):
```python
def post_order_iterative(root: TreeNode):
if not root:
return
stack1 = [root]
stack2 = []
while stack1:
node = stack1.pop()
stack2.append(node)
if node.left:
stack1.append(node.left)
if node.right:
stack1.append(node.right)
while stack2:
node = stack2.pop()
print(node.val, end=' ')
```
二叉树的层次遍历:
```python
def level_order(root: TreeNode):
if not root:
return
queue = [root]
while queue:
level_size = len(queue)
for i in range(level_size):
node = queue.pop(0)
print(node.val, end=' ')
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
print()
```
以上代码均为 Python 代码,具体实现细节可能与其他语言略有不同,但思路一致。
阅读全文