LeetCode 94. Binary Tree Inorder Traversal

Post by ailswan Sep.24, 2023

94. Binary Tree Inorder Traversal

Problem Statement

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

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

Example:

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

Input: root = [] Output: []

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

Solution Approach

recursion

Algorithm

  1. Initialization: Create an empty list res for the result.
  2. Recursive Traversal: Use the inorder function to visit the left child, current node, and then the right child.
  3. Execution: If the root exists, begin the traversal with the inorder function and return the res list.

Implement

    class Solution:
      def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
          res = []
          def inorder(node):
              if node.left:
                  inorder(node.left)
              res.append(node.val)
              if node.right:
                  inorder(node.right)
                  
          if root:
              inorder(root)
          return res