Problem
Given theroot of a binary tree, return the inorder traversal of its nodes’ values.
Examples
Constraints
- The number of nodes in the tree is in the range
[0, 100] -100 <= Node.val <= 100
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 94 with 15 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 94 # by problem number
lcpy gen -s binary_tree_inorder_traversal # by problem name
root of a binary tree, return the inorder traversal of its nodes’ values.
Input: root = [1,null,2,3]
Output: [1,3,2]
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [4,2,6,5,7,1,3,9,8]
Input: root = []
Output: []
Input: root = [1]
Output: [1]
[0, 100]-100 <= Node.val <= 100from leetcode_py import TreeNode
class Solution:
# Time: O(n)
# Space: O(h) where h is the height of the tree
def inorder_traversal(self, root: TreeNode[int] | None) -> list[int]:
result: list[int] = []
stack: list[TreeNode[int]] = []
current: TreeNode[int] | None = root
while current or stack:
while current:
stack.append(current)
current = current.left
current = stack.pop()
result.append(current.val)
current = current.right
return result
| Time | Space |
|---|---|
| O(n) | O(h) where h is the height of the tree |