本帖最后由 Stubborn 于 2020-5-30 02:43 编辑 class Tree:
class Node:
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def create(self, string: str):
data = string.split(',')
root = Tree.Node(data.pop(0), None, None)
l = [root]
while True:
try:
node = l.pop(0)
node.left = Tree.Node(
data.pop(0), None, None
)
l.append(node.left)
node.right = Tree.Node(
data.pop(0), None, None
)
l.append(node.right)
except:
return root
def traversal(self, node):
if node is None: return
# 打印前序遍历
# print(node.value)
self.traversal(node.left)
# 打印中序遍历
# print(node.value)
self.traversal(node.right)
# 打印后续遍历
# print(node.value)
def traversal(self, node, result=None):
# 需要输出列表的话
if result is None:
result = list()
if node is None: return
result.append(node.value)
self.traversal(node.left, result)
self.traversal(node.right, result)
return result
a = Tree()
root = a.create("1,2,3,4")
a.traversal(root)
# >>> 1 2 4 3
备注,输入的 # 我这里没有处理,思考下,自己做处理。 |