The problem can be solved in one traverse over the tree if you pass additional signs to the function. I pass left
and right
flags to indicate if I go along the left edge or right edge:
def display_tree_perimeter(root):
result = ""
stack_right = []
def walk_and_print(root, left, right):
nonlocal result
this_was_printed = False
if root.left:
if left:
if not this_was_printed:
result += str(root.data) + " "
this_was_printed = True
walk_and_print(root.left, True, False)
else:
walk_and_print(root.left, False, False)
if root.right:
if right:
if not this_was_printed:
stack_right.append(root.data)
this_was_printed = True
walk_and_print(root.right, False, True)
else:
walk_and_print(root.right, False, False)
if root.left is None and root.right is None:
if not this_was_printed:
result += str(root.data) + " "
this_was_printed = False
walk_and_print(root, True, True)
while stack_right:
result += str(stack_right.pop()) + " "
return result