Python构建二叉树

B站影视 2024-12-30 07:14 2

摘要:class Node:def __init__(self, data):self.left = Noneself.right = Noneself.data = data# Insert Nodedef insert(self, data):if self.d

class Node:def __init__(self, data):self.left = Noneself.right = Noneself.data = data# Insert Nodedef insert(self, data):if self.data:if data self.data:if self.right is None:self.right = Node(data)else:self.right.insert(data)else:self.data = data# Print the Treedef PrintTree(self):if self.left:self.left.PrintTreeprint( self.data),if self.right:self.right.PrintTree# 中序遍历# Left -> root -> Rightdef inorderTraversal(self, root):res = if root:res = self.inorderTraversal(root.left)res.append(root.data)res = res + self.inorderTraversal(root.right)return resroot = Node(27)root.insert(14)root.insert(35)root.insert(10)root.insert(19)root.insert(31)root.insert(42)print(root.inorderTraversal(root))

来源:小亮课堂

相关推荐