编写一段代码 要求建立二叉树并实现二叉树的遍历,先序遍历采用递归算法实现,层次遍历用非递归算法实现
时间: 2024-03-24 14:38:36 浏览: 81
好的,我可以为您提供一个Python代码示例,实现二叉树的构建和遍历。
首先,我们定义一个二叉树节点的类:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
接下来,我们定义一个函数 build_tree(),通过输入一个列表来构造二叉树。列表中按照层次遍历的顺序给出每个节点的值,如果该节点为空则用 None 表示。例如,输入列表 [1, 2, 3, None, 4, None, 5] 表示如下二叉树:
```
1
/ \
2 3
\ \
4 5
```
代码如下:
```python
from queue import Queue
def build_tree(nodes):
if not nodes:
return None
root = TreeNode(nodes[0])
q = Queue()
q.put(root)
i = 1
while not q.empty():
node = q.get()
if i < len(nodes) and nodes[i] is not None:
node.left = TreeNode(nodes[i])
q.put(node.left)
i += 1
if i < len(nodes) and nodes[i] is not None:
node.right = TreeNode(nodes[i])
q.put(node.right)
i += 1
return root
```
然后,我们定义一个函数 preorder_recursive(),采用递归算法实现先序遍历。先访问根节点,再先序遍历左子树,最后先序遍历右子树。
```python
def preorder_recursive(root):
if not root:
return []
res = []
res.append(root.val)
res.extend(preorder_recursive(root.left))
res.extend(preorder_recursive(root.right))
return res
```
最后,我们定义一个函数 levelorder(),采用非递归算法实现层次遍历。使用队列保存每一层的节点,先将根节点入队,然后依次出队每一个节点,将该节点的左右子节点入队,直到队列为空。
```python
def levelorder(root):
if not root:
return []
res = []
q = Queue()
q.put(root)
while not q.empty():
level_size = q.qsize()
level = []
for i in range(level_size):
node = q.get()
level.append(node.val)
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
res.append(level)
return res
```
这样,我们就完成了二叉树的构建和遍历的代码实现。完整代码如下:
```python
from queue import Queue
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(nodes):
if not nodes:
return None
root = TreeNode(nodes[0])
q = Queue()
q.put(root)
i = 1
while not q.empty():
node = q.get()
if i < len(nodes) and nodes[i] is not None:
node.left = TreeNode(nodes[i])
q.put(node.left)
i += 1
if i < len(nodes) and nodes[i] is not None:
node.right = TreeNode(nodes[i])
q.put(node.right)
i += 1
return root
def preorder_recursive(root):
if not root:
return []
res = []
res.append(root.val)
res.extend(preorder_recursive(root.left))
res.extend(preorder_recursive(root.right))
return res
def levelorder(root):
if not root:
return []
res = []
q = Queue()
q.put(root)
while not q.empty():
level_size = q.qsize()
level = []
for i in range(level_size):
node = q.get()
level.append(node.val)
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
res.append(level)
return res
if __name__ == '__main__':
nodes = [1, 2, 3, None, 4, None, 5]
root = build_tree(nodes)
print('Preorder Traversal (Recursive):', preorder_recursive(root))
print('Levelorder Traversal:', levelorder(root))
```
输出结果如下:
```
Preorder Traversal (Recursive): [1, 2, 4, 3, 5]
Levelorder Traversal: [[1], [2, 3], [4, 5]]
```
阅读全文