python代码实现二叉树结构以及二叉树的常见操作
时间: 2023-04-05 15:03:49 浏览: 123
可以回答这个问题。二叉树是一种常见的数据结构,可以用 Python 实现。以下是一个简单的二叉树实现示例:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, val):
if not self.root:
self.root = TreeNode(val)
else:
self._insert(val, self.root)
def _insert(self, val, node):
if val < node.val:
if node.left:
self._insert(val, node.left)
else:
node.left = TreeNode(val)
else:
if node.right:
self._insert(val, node.right)
else:
node.right = TreeNode(val)
def search(self, val):
return self._search(val, self.root)
def _search(self, val, node):
if not node:
return False
elif node.val == val:
return True
elif val < node.val:
return self._search(val, node.left)
else:
return self._search(val, node.right)
def inorder_traversal(self):
res = []
self._inorder_traversal(self.root, res)
return res
def _inorder_traversal(self, node, res):
if node:
self._inorder_traversal(node.left, res)
res.append(node.val)
self._inorder_traversal(node.right, res)
def preorder_traversal(self):
res = []
self._preorder_traversal(self.root, res)
return res
def _preorder_traversal(self, node, res):
if node:
res.append(node.val)
self._preorder_traversal(node.left, res)
self._preorder_traversal(node.right, res)
def postorder_traversal(self):
res = []
self._postorder_traversal(self.root, res)
return res
def _postorder_traversal(self, node, res):
if node:
self._postorder_traversal(node.left, res)
self._postorder_traversal(node.right, res)
res.append(node.val)
```
这个二叉树实现包括插入、搜索、中序遍历、前序遍历和后序遍历等常见操作。
阅读全文