LeetCode 94: Binary Tree Inorder Traversal

Source

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]
  1. Iteration
class Solution:
    def inorderTraversal(self, root: 'TreeNode') -> 'List[int]':
        if not root:
            return []
        return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
  1. Recursion
class Solution:
    def inorderTraversal(self, root: 'TreeNode') -> 'List[int]':
        stack = []
        p = root
        res = []
        while stack or p:
            while p:
                stack.append(p)
                p = p.left
            node = stack.pop()
            res.append(node.val)
            p = node.right
        return res