Pre Order Traversal of a Binary Tree (Leetcode 144)

Node -> Left -> Right

Problem Link: https://leetcode.com/problems/binary-tree-preorder-traversal/

Recursive:

class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        
        global ans
        ans=[]
        
        def fun(root):
            if(root is None):
                return
            ans.append(root.val)
            fun(root.left)
            fun(root.right)

        fun(root)
        return ans

Iterative:

class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        self.s=[]
        self.ans=[]
        curr=root
        while(1):
            if(curr is None and len(self.s)==0):
                return self.ans
            if(curr is not None):
                self.ans.append(curr.val)
                self.s.append(curr)
                curr=curr.left
            else:
                curr=self.s.pop()
                curr=curr.right
        return self.ans

Last updated