编写一个程序实现二叉树的先序遍历、中序遍历和后序遍历的递归算法的完整代码
时间: 2023-06-02 22:07:21 浏览: 220
好的,以下为二叉树先序、中序、后序遍历的递归算法完整代码:
```python
class Node:
def __init__(self, val=None):
self.val = val
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, val):
node = Node(val)
if self.root is None:
self.root = node
else:
curr = self.root
while True:
if val < curr.val:
if curr.left is None:
curr.left = node
break
else:
curr = curr.left
elif val > curr.val:
if curr.right is None:
curr.right = node
break
else:
curr = curr.right
def preorder(self, node):
if node is not None:
print(node.val, end=' ')
self.preorder(node.left)
self.preorder(node.right)
def inorder(self, node):
if node is not None:
self.inorder(node.left)
print(node.val, end=' ')
self.inorder(node.right)
def postorder(self, node):
if node is not None:
self.postorder(node.left)
self.postorder(node.right)
print(node.val, end=' ')
```
以上代码中,Node 类是二叉树节点的定义,BinarySearchTree 类是二叉搜索树的定义。insert 方法是插入节点的操作,preorder、inorder、postorder 方法是分别进行先序、中序、后序遍历的递归算法的实现。
如果您有其他问题需要帮助,请继续提问。
阅读全文