编写运用二叉树的构造与遍历的代码
时间: 2023-12-18 12:04:07 浏览: 60
二叉树上机作业-二叉树讲义
好的,我可以为您提供一个简单的二叉树构造与遍历的代码示例,使用的是Python语言。
首先,我们定义一个二叉树节点的类:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
接下来,我们通过输入一个列表来构造二叉树。列表中按照层次遍历的顺序给出每个节点的值,如果该节点为空则用 None 表示。例如,输入列表 [1, 2, 3, None, 4, None, 5] 表示如下二叉树:
```
1
/ \
2 3
\ \
4 5
```
代码如下:
```python
from queue import Queue
def buildTree(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
```
最后,我们可以实现三种遍历方式:前序遍历、中序遍历和后序遍历。
```python
def preorderTraversal(root):
if not root:
return []
res = []
stack = []
node = root
while node or stack:
while node:
res.append(node.val)
stack.append(node)
node = node.left
node = stack.pop()
node = node.right
return res
def inorderTraversal(root):
if not root:
return []
res = []
stack = []
node = root
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
res.append(node.val)
node = node.right
return res
def postorderTraversal(root):
if not root:
return []
res = []
stack = []
node = root
while node or stack:
while node:
if node.right:
stack.append(node.right)
stack.append(node)
node = node.left
node = stack.pop()
if stack and node.right == stack[-1]:
stack[-1] = node
node = node.right
else:
res.append(node.val)
node = None
return res
```
这样,我们就完成了一个简单的二叉树构造与遍历的代码实现。
阅读全文