educative.io

Educative

Question For Print Tree Perimeter -- Iterative solution

I really don’t understand print_leaf_nodes part. How we go from leaf node 10 to node 60? I spent so much time on this already. If someone could help me out, I highly appreciate it! Below is the solution code I copied and pasted. I added some code in that part to demonstrate my point. I hope my question makes sense. Thank you!

def print_left_perimeter(root, result):
  while root != None:
    curr_val = root.data

    if root.left != None:
      root = root.left
    elif root.right != None:
      root = root.right
    else: # leaf node
      break
    # print(str(curr_val) + " ", end="")
    result.append(str(curr_val) + " ")

def print_right_perimeter(root, result):
  r_values = [] # stack for right side values.

  while root != None:
    curr_val = root.data

    if root.right != None:
      root = root.right
    elif root.left != None:
      root = root.left
    else: # leaf node
      break
    r_values.append(curr_val)

  while len(r_values) != 0:
    # print(str(r_values.pop()) + " ", end="")
    result.append(str(r_values.pop()) + " ")

def print_leaf_nodes(root, result):
  """
  START: my added code for understanding
  """
  if root != None:
    print("enter leaf", root.data)
  else:
    print("enter leaf", None)
  """
  END: my added code ends
  """

  if root != None:
    print_leaf_nodes(root.left, result)

    if root.left == None and root.right == None:
      """
      START: my added code for understanding
      """
      if root:
        print("append to leaf to result", root.data)
      else:
        print("append to leaf to result", None)
      """
      END: my added code ends
      """
      # print(str(root.data) + " ", end="")
      result.append(str(root.data) + " ")

    print_leaf_nodes(root.right, result)

def display_tree_perimeter(root):
  result = []
  if root != None:
    # print(str(root.data) + " ", end="")
    result.append(str(root.data) + " ")

    print_left_perimeter(root.left, result)

    if root.left != None or root.right != None:
      print_leaf_nodes(root, result)

    print_right_perimeter(root.right, result) 
  return ('').join(result)

arr = [100,50,200,25,60,350,10,70,400]
root = create_BST(arr)
print("\nPrint tree perimeter\n")
print(display_tree_perimeter(root))