In Order Traversal of a Binary Tree (Leetcode 94)

Left -> Node-> Right

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

Recursive:

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

Iterative:

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

Last updated