python二叉树的创建代码
时间: 2023-11-19 11:05:06 浏览: 78
下面是Python中二叉树的创建代码,其中包括节点类和二叉树类:
```python
class Node:
def __init__(self, val=None):
self.val = val
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, val):
new_node = Node(val)
if self.root is None:
self.root = new_node
else:
queue = [self.root]
while queue:
curr = queue.pop(0)
if curr.left is None:
curr.left = new_node
break
elif curr.right is None:
curr.right = new_node
break
else:
queue.append(curr.left)
queue.append(curr.right)
def inorder_traversal(self, node):
if node is not None:
self.inorder_traversal(node.left)
print(node.val, end=" ")
self.inorder_traversal(node.right)
def preorder_traversal(self, node):
if node is not None:
print(node.val, end=" ")
self.preorder_traversal(node.left)
self.preorder_traversal(node.right)
def postorder_traversal(self, node):
if node is not None:
self.postorder_traversal(node.left)
self.postorder_traversal(node.right)
print(node.val, end=" ")
```
这里通过节点类和二叉树类来实现二叉树的创建,节点类中包含节点的值和左右子树指针,二叉树类中包含根节点指针以及插入节点、遍历等方法。其中插入节点的方法使用了广度优先搜索,遍历的方法分别是中序遍历、前序遍历、后序遍历。
阅读全文