class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value < self.value:
if self.left is None:
self.left = TreeNode(value)
else:
self.left.insert(value)
else:
if self.right is None:
self.right = TreeNode(value)
else:
self.right.insert(value)
使用上述代碼定義了一個簡單的TreeNode
類,實現(xiàn)了樹的插入操作??梢酝ㄟ^調(diào)用insert
方法向樹中插入新的節(jié)點。