class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Tree:
def __init__(self, node=None):
self.root = node
def add(self, item=None):
node = Node(val=item)
if not self.root or self.root.val is None:
self.root = node
else:
queue = []
queue.append(self.root)
while True:
current_node = queue.pop(0)
if current_node.val is None:
continue
if not current_node.left:
current_node.left = node
return
elif not current_node.right:
current_node.right = node
return
else:
queue.append(current_node.left)
queue.append(current_node.right)
def fontTranverse(self, node, tranverseList=[]):
if node is None:
return tranverseList
else:
tranverseList.append(node.val)
if node.left is not None:
tranverseList = self.fontTranverse(node.left, tranverseList)
if node.right is not None:
tranverseList = self.fontTranverse(node.right, tranverseList)
return tranverseList
def midTranverse(self, node, tranverseList=[]):
if node is None:
return tranverseList
else:
if node.left is None:
tranverseList.append(node.val)
else:
tranverseList = self.midTranverse(node.left, tranverseList)
tranverseList.append(node.val)
if node.right is not None:
tranverseList = self.midTranverse(node.right, tranverseList)
return tranverseList
def backTranverse(self, node, tranverseList=[]):
if node is None:
return tranverseList
else:
if node.left is None:
tranverseList.append(node.val)
return tranverseList
else:
tranverseList = self.backTranverse(node.left, tranverseList)
if node.right is not None:
tranverseList = self.backTranverse(node.right, tranverseList)
tranverseList.append(node.val)
return tranverseList
tree = Tree()
for i in range(10):
if i == 3:
i = None
tree.add(i)
print(tree.fontTranverse(tree.root))
print(tree.midTranverse(tree.root))
print(tree.backTranverse(tree.root))
python 二叉树
最新推荐文章于 2024-11-04 21:51:40 发布