python 二叉树 前序名
https://preview.cloud.189.cn/image/imageAction?param=95F4AAFBB52C89B248AFA67C0A6D748AB3C56CC43E380EEB5F1B3B4CFDD0E15BA3AEE222A1A65330479615D6143DCA8EEF6878FB23BD456121D9AEC71148C88234AD0E275FA4F0B4E802D789F63287AC1C6156C83E5D40350CE552DE求解 本帖最后由 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 =
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
备注,输入的 # 我这里没有处理,思考下,自己做处理。
页:
[1]