Leetcode 94 Solution

This article provides solution to leetcode question 94 (binary-tree-inorder-traversal)

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

Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        s = []

        if not root:
            return s

        s.append((root, 0))

        ans = []
        while s:
            node, state = s.pop()

            if state == 0:
                s.append((node, 1))

                if node.left:
                    s.append((node.left, 0))
            elif state == 1:
                ans.append(node.val)

                if node.right:
                    s.append((node.right, 0))

        return ans