30min
The order of in-order traversal is left - middle - right
recursion
It’s very easy with recursion
var inorderTraversal = function(root) {
var res = []
if (!root) {
return res
}
var travel = function (node) {
node.left && travel(node.left)
res.push(node.val)
node.right && travel(node.right)
}
travel(root)
return res
};
```Iteration
The iterative steps are more complicated because the root node is not output first, so the root node needs to be retained
1. Push the root node onto the stack and check if it has a left child. If so, continue pushing until you reach a leaf node.
1. Pop the stack, output, and check if it has a right child. If so, push it onto the stack and continue with step 2.
```javascript
var inorderTraversal = function(root) {
var stack = []
var res = []
if (!root) return res
stack.push(root)
while(root.left) {
stack.push(root.left)
root = root.left }
while(stack.length) {
// At this point the top of the stack is the leftmost node in the tree var node = stack.pop()
res.push(node.val)
// There is a right node, push it into the stack and continue to look for the left node if (node.right) {
node = node.right stack.push(node)
while(node.left) {
stack.push(node.left)
node = node.left }
}
}
return res
};