Binary Tree Preorder Traversal in Python

Suppose we have a binary tree. We have to return the preorder traversal of that tree. So if the tree is like −

Then the preorder traversal will be: [3,9,20,15,7]

To solve this, we will follow these steps −

  • make empty lists called res and st.
  • node := root
  • while node or st is not empty
    • while node is not null, then
      • insert val of node into res, insert node into st and set node := left of node
    • temp := last element of st, and delete last element of st
    • if right of temp is available, then
      • node := right of temp
  • return res

Let us see the following implementation to get better understanding −


 Live Demo

class TreeNode:
   def __init__(self, data, left = None, right = None): = data
      self.left = left
      self.right = right
def insert(temp,data):
   que = []
   while (len(que)):
      temp = que[0]
      if (not temp.left):
         temp.left = TreeNode(data)
      if (not temp.right):
         temp.right = TreeNode(data)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
   insert(Tree, element)
   return Tree
class Solution(object):
   def preorderTraversal(self, root):
      res = []
      st = []
      node = root
      while node or st:
         while node:
            if != None:
            node = node.left
         temp = st[-1]
         if temp.right:
            node = temp.right
   return res
ob1 = Solution()
head = make_tree([3,9,20,None,None,15,7])




[3, 9, 20, 15, 7]

Updated on: 04-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started