Given the root
of a binary tree, return the inorder traversal of its nodes' values.
For example, if the input is root = [1,null,2,3]
, the output should be [1,3,2]
because you visit the left subtree (None), then the root (1), then the right subtree (2 which has left child 3, so you visit 3 then 2). Another example, if the input is root = [1,2,3,4,5,null,8,null,null,6,7,9]
, then the output should be [4,2,6,5,7,1,3,9,8]
because that's the inorder traversal of the tree.
Recursive solution is trivial, could you do it iteratively?
## Question: Binary Tree Inorder Traversal
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]`
The most intuitive way to perform an inorder traversal is using recursion. The inorder traversal visits the left subtree, then the current node, then the right subtree.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> list[int]:
result = []
def inorder(node: TreeNode):
if not node:
return
inorder(node.left)
result.append(node.val)
inorder(node.right)
inorder(root)
return result
An iterative solution uses a stack to keep track of the nodes. The algorithm proceeds as follows:
class Solution:
def inorderTraversal(self, root: TreeNode) -> list[int]:
result = []
stack = []
curr = root
while curr or stack:
while curr:
stack.append(curr)
curr = curr.left
curr = stack.pop()
result.append(curr.val)
curr = curr.right
return result
None
, the algorithm should return an empty list []
.[1]
.