Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 10, 2017 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/e33f945d50a8cb56fdf940eb504e5583 to your computer and use it in GitHub Desktop.
Save InterviewBytes/e33f945d50a8cb56fdf940eb504e5583 to your computer and use it in GitHub Desktop.
Inorder traversal Iterative approach
package com.interviewbytes.trees;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class InorderTraversalIterative {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
if (current != null) {
stack.push(current);
current = current.left;
} else {
current = stack.pop();
list.add(current.val);
current = current.right;
}
}
return list;
}
}
package com.interviewbytes.trees;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment