Binary Tree Preorder Traversal in Python

C++Server Side ProgrammingProgramming

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 −

class Solution(object):
   def preorderTraversal(self, root):
      :type root: TreeNode
      :rtype: List[int]
      res = []
      st = []
      node = root
      while node or st:
         while node:
            node = node.left
         temp = st[-1]
         if temp.right:
            node = temp.right
      return res




Published on 03-Feb-2020 10:49:00