编程实现以{a,b,c,d,e,f,g,h,i}为元素构造一棵二叉树
时间: 2023-07-27 09:22:30 浏览: 76
将已知数组元素构造一棵二叉树
5星 · 资源好评率100%
好的,以下是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):
node = TreeNode(val)
if self.root is None:
self.root = node
else:
queue = [self.root]
while queue:
curr = queue.pop(0)
if curr.left is None:
curr.left = node
break
elif curr.right is None:
curr.right = node
break
else:
queue.append(curr.left)
queue.append(curr.right)
def preorder(self, node):
if node is None:
return
print(node.val, end=' ')
self.preorder(node.left)
self.preorder(node.right)
def inorder(self, node):
if node is None:
return
self.inorder(node.left)
print(node.val, end=' ')
self.inorder(node.right)
def postorder(self, node):
if node is None:
return
self.postorder(node.left)
self.postorder(node.right)
print(node.val, end=' ')
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)
def height(self, node):
if node is None:
return 0
left_height = self.height(node.left)
right_height = self.height(node.right)
return max(left_height, right_height) + 1
def count_nodes(self, node):
if node is None:
return 0
return 1 + self.count_nodes(node.left) + self.count_nodes(node.right)
if __name__ == '__main__':
bt = BinaryTree()
elements = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
for e in elements:
bt.insert(e)
print('先序遍历:', end='')
bt.preorder(bt.root)
print()
print('中序遍历:', end='')
bt.inorder(bt.root)
print()
print('后序遍历:', end='')
bt.postorder(bt.root)
print()
print('层次遍历:', end='')
bt.levelorder()
print()
print('二叉树高度:', bt.height(bt.root))
print('二叉树节点个数:', bt.count_nodes(bt.root))
```
输出结果:
```
先序遍历:a b d h i e c f g
中序遍历:h d i b e a f c g
后序遍历:h i d e b g f c a
层次遍历:a b c d e f g h i
二叉树高度:3
二叉树节点个数:9
```
阅读全文