构建一颗二叉查找树并实现其前序、中序、后序及层序遍
二叉查找树是一种特殊的二叉树,其中每个节点的值比其左子树中的值大,比其右子树中的值小。下面是构建一颗二叉查找树的Python代码:
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
if root is None:
return TreeNode(val)
elif val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
def preorder(root):
if root is None:
return
print(root.val, end=' ')
preorder(root.left)
preorder(root.right)
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.val, end=' ')
inorder(root.right)
def postorder(root):
if root is None:
return
postorder(root.left)
postorder(root.right)
print(root.val, end=' ')
def levelorder(root):
if root is None:
return
queue = [root]
while queue:
node = queue.pop(0)
print(node.val, end=' ')
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# 构建二叉查找树
root = None
values = [8, 3, 10, 1, 6, 14, 4, 7, 13]
for val in values:
root = insert(root, val)
print("前序遍历结果:")
preorder(root)
print("\n中序遍历结果:")
inorder(root)
print("\n后序遍历结果:")
postorder(root)
print("\n层序遍历结果:")
levelorder(root)
运行结果如下:
前序遍历结果:
8 3 1 6 4 7 10 14 13
中序遍历结果:
1 3 4 6 7 8 10 13 14
后序遍历结果:
1 4 7 6 3 13 14 10 8
层序遍历结果:
8 3 10 1 6 14 4 7 13
``
原文地址: https://www.cveoy.top/t/topic/ig4J 著作权归作者所有。请勿转载和采集!