Problem
Given the root
of a binary tree, return the "inorder traversal" of its node's values.
Approach
Firstly, you're maybe thinking what is inorder traversal
? Well it means:
For each node:
- Visit the left subtree first
- Then visit the current node
- Then visit the right subtree
Example:
6
/ \
4 8
/ \ \
3 5 9
/
1
In‑order traversal steps:
- Start at root 6 → go left to 4
- From 4 → go left to 3
- From 3 → go left to 1 → visit 1 (no left child)
- Back to 3 → visit 3 → no right child → back to 4
- Visit 4 → go right to 5 → visit 5 → back to 6
- Visit 6 → go right to 8
- From 8 → no left child → visit 8 → go right to 9 → visit 9
So we go as far left as we can before returning back up the branch and going right, until we try to get left again as far as we can and so on.
We achieve this using a Stack
which works on a LIFO (last in first out) approach.
We keep going left, pushing nodes onto the stack.
When you can’t go left anymore,
Pop()
from the stack, visit the node and move to its right child.Repeat until both current is null and the stack is empty.
Whatever result we have at the end is our inorder-traversal
of our binary tree.
Code
public IList<int> InorderTraversal(TreeNode root) {
var result = new List<int>();
var stack = new Stack<TreeNode>();
var current = root;
while (current != null || stack.Count > 0)
{
while (current != null)
{
stack.Push(current);
current = current.left;
}
current = stack.Pop();
result.Add(current.val);
current = current.right;
}
return result.ToArray();
}
Top comments (0)