# Binary Tree Inorder Traversal

94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree [1,null,2,3],

``````   1
\
2
/
3
``````

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

``````class Solution {
func inorderTraversal(_ root: TreeNode?) -> [Int] {
var result: [Int] = []

helper(root, &result)

return result
}

func helper(_ root: TreeNode?, _ result: inout [Int]) {
guard let root = root else {
return
}

helper(root.left, &result)
result.append(root.val)

helper(root.right, &result)
}
}
``````
``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     public var val: Int
*     public var left: TreeNode?
*     public var right: TreeNode?
*     public init(_ val: Int) {
*         self.val = val
*         self.left = nil
*         self.right = nil
*     }
* }
*/
class Solution {
func inorderTraversal(_ root: TreeNode?) -> [Int] {
if root == nil {
return []
}

var result: [Int] = []

var stack: [TreeNode] = []
var node = root

while !stack.isEmpty || node != nil {
if let n = node {
stack.append(n)

node = n.left
} else {
let n = stack.removeLast()
result.append(n.val)

node = n.right
}
}

return result
}
}
``````
``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}

Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;

while (!stack.isEmpty() || node != null) {
if (node != null) {
stack.push(node);

node = node.left;
} else {
node = stack.pop();