用python写一个二叉树代码
时间: 2024-04-30 11:21:26 浏览: 87
python 平衡二叉树实现代码示例
下面是一个简单的Python二叉树代码示例:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, val):
newNode = TreeNode(val)
if self.root is None:
self.root = newNode
else:
current = self.root
while True:
if val < current.val:
if current.left is None:
current.left = newNode
break
else:
current = current.left
else:
if current.right is None:
current.right = newNode
break
else:
current = current.right
def inorderTraversal(self, node):
if node is not None:
self.inorderTraversal(node.left)
print(node.val)
self.inorderTraversal(node.right)
tree = BinaryTree()
tree.insert(5)
tree.insert(3)
tree.insert(7)
tree.insert(1)
tree.insert(9)
tree.inorderTraversal(tree.root)
```
上述代码实现了一个简单的二叉树。其中,TreeNode类表示每个节点,BinaryTree类表示整个二叉树。在BinaryTree类中,insert方法用于向二叉树中插入新的节点,inorderTraversal方法用于按顺序遍历并打印整个二叉树。
阅读全文