Given the root of a binary tree, return the inorder traversal of its nodes' values.

 

Example 1:

Input: root = [1,null,2,3]
Output: [1,3,2]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

 

Follow up: Recursive solution is trivial, could you do it iteratively?



SolvingApproachs:

  1. Recursive way
def inorderTraversal(self, root):
        """ Inorder Tree traversal with recursive function call.  left -> root -> right """
        if root:
            self.inorderTraversal(root.left)
            #print(root.val)
            self.result.append(root.val)
            self.inorderTraversal(root.right)

        return self.result
  1. Iterative way
def inorder_traversal_iterative(self, root):
        """ Using Iterative method to traverse tree in in-order manner."""
        current = root
        stack = []

        while current or stack:
            while current:
                stack.append(current)
                current = current.left

            # list.pop() has default -1, which is the last element (recent)
            current = stack.pop()
            self.result.append(current.val)
            current = current.right

        return self.result

Random Note


From python 3.7 dict guarantees that order will be kept as they inserted, and popitem will use LIFO order but we need FIFO type system. so we need OrderedDict which have popIten(last = T/F) for this req. One thing, next(iter(dict)) will return the first key of the dict