class TreeNode:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def create_binary_tree(input_list=[]):
"""前序构建二叉树"""
if input_list is None or len(input_list)==0: # 首先判断是不是None以及是不是空
return None
data = input_list.pop(0) # 根节点
if data is None:
return None
node = TreeNode(data)
node.left = create_binary_tree(input_list)
node.right = create_binary_tree(input_list)
return node
def pre_order_traversal_with_stack(node):
"""非递归的前序遍历"""
stack = []
while node is not None or len(stack) > 0:
while node is not None:
print(node.data)
stack.append(node)
node = node.left
if len(stack) > 0:
node = stack.pop()
node = node.right
if __name__ == '__main__':
my_input_list = [3,2,9,None,None,10,None,None,8,None,4]
root = create_binary_tree(my_input_list)
print("前序遍历")
pre_order_traversal_with_stack(root)
输出:
前序遍历
3
2
9
10
8
4