Given the root of a binary tree, return the inorder traversal of its nodes’ values.
In an inorder traversal, for each node:
Example:
Input: root = [1, null, 2, 3]
Output: [1, 3, 2]
Constraints:
[0, 100]
.-100 <= Node.val <= 100
We can solve this problem iteratively or recursively. Here, we’ll show both methods.
from typing import Optional, List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorderTraversal(root: Optional[TreeNode]) -> List[int]:
def helper(node: Optional[TreeNode], result: List[int]):
if not node:
return
helper(node.left, result)
result.append(node.val)
helper(node.right, result)
result = []
helper(root, result)
return result
def inorderTraversal(root: Optional[TreeNode]) -> List[int]:
result, stack = [], []
current = 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
Both the recursive and iterative methods have the same time complexity.
Both methods will perform efficiently within the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?