用python语言定义一个包含结点相关信息的二叉树结点类和一个包含二叉树定义及其基本操作的二叉树的类
时间: 2023-11-14 21:21:45 浏览: 78
二叉树结点类的定义:
```python
class BinaryTreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
```
二叉树类的定义:
```python
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, val):
node = BinaryTreeNode(val)
if self.root is None:
self.root = node
else:
parent = None
current = self.root
while current is not None:
parent = current
if val < current.val:
current = current.left
else:
current = current.right
if val < parent.val:
parent.left = node
else:
parent.right = node
def search(self, val):
current = self.root
while current is not None:
if current.val == val:
return True
elif val < current.val:
current = current.left
else:
current = current.right
return False
def inorder(self):
def _inorder(node):
if node is None:
return
_inorder(node.left)
print(node.val, end=' ')
_inorder(node.right)
_inorder(self.root)
print()
def preorder(self):
def _preorder(node):
if node is None:
return
print(node.val, end=' ')
_preorder(node.left)
_preorder(node.right)
_preorder(self.root)
print()
def postorder(self):
def _postorder(node):
if node is None:
return
_postorder(node.left)
_postorder(node.right)
print(node.val, end=' ')
_postorder(self.root)
print()
def levelorder(self):
if self.root is None:
return
queue = [self.root]
while queue:
node = queue.pop(0)
print(node.val, end=' ')
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
print()
```
这里定义了二叉树的基本操作,包括插入、查找和遍历(前序、中序、后序和层序遍历)。
阅读全文