classSolution{List<Integer> res =newArrayList();publicList<Integer>inorderTraversal(TreeNode root){inorder(root);return res;}privatevoidinorder(TreeNode node){if(node ==null)return;inorder(node.left);
res.add(node.val);inorder(node.right);}}
Iterative
classSolution{publicList<Integer>inorderTraversal(TreeNode root){List<Integer> res =newArrayList();Stack<TreeNode> stack =newStack();TreeNode cur = root;// Traverse the whole treewhile(cur !=null||!stack.isEmpty()){// Go to the left whenever possiblewhile(cur !=null){
stack.push(cur);
cur = cur.left;}// Reach a null, pop the parent node
cur = stack.pop();// Add to the result
res.add(cur.val);// Go to the right
cur = cur.right;}return res;}}