二叉树的基本操作源代码
时间: 2023-07-07 09:45:19 浏览: 86
二叉树的基本操作的源代码
以下是基本操作的二叉树源代码(使用Python语言实现):
```python
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def create_node(self, val):
return Node(val)
def insert_node(self, node, val):
if not node:
return self.create_node(val)
if val < node.val:
node.left = self.insert_node(node.left, val)
elif val > node.val:
node.right = self.insert_node(node.right, val)
return node
def inorder_traversal(self, node):
if not node:
return
self.inorder_traversal(node.left)
print(node.val, end=" ")
self.inorder_traversal(node.right)
def delete_node(self, node, val):
if not node:
return node
if val < node.val:
node.left = self.delete_node(node.left, val)
elif val > node.val:
node.right = self.delete_node(node.right, val)
else:
if not node.left:
temp = node.right
node = None
return temp
elif not node.right:
temp = node.left
node = None
return temp
temp = self.get_min_value_node(node.right)
node.val = temp.val
node.right = self.delete_node(node.right, temp.val)
return node
def get_min_value_node(self, node):
while node.left:
node = node.left
return node
def search_node(self, node, val):
if not node:
return None
if val == node.val:
return node
if val < node.val:
return self.search_node(node.left, val)
else:
return self.search_node(node.right, val)
def modify_node(self, node, old_val, new_val):
if not node:
return None
node = self.delete_node(node, old_val)
node = self.insert_node(node, new_val)
return node
def count_nodes(self, node):
if not node:
return 0
return 1 + self.count_nodes(node.left) + self.count_nodes(node.right)
def get_depth(self, node):
if not node:
return 0
left_depth = self.get_depth(node.left)
right_depth = self.get_depth(node.right)
return max(left_depth, right_depth) + 1
```
上述代码实现了二叉树的节点插入、遍历、删除、查找、修改、计算节点数量和计算树的深度等基本操作。
阅读全文