Skip to content

Instantly share code, notes, and snippets.

@sdpatil
Created August 12, 2017 19:40
Show Gist options
  • Select an option

  • Save sdpatil/3998a5f1cd3cd56151d4a780cd96b38a to your computer and use it in GitHub Desktop.

Select an option

Save sdpatil/3998a5f1cd3cd56151d4a780cd96b38a to your computer and use it in GitHub Desktop.
Implement an inorder traversal with o(1) space
import java.util.ArrayList;
import java.util.List;
/*
Problem: Perform in order traversal of binary tree without using recursion or stack (No space)
*/
public class InOrderTraversalWithConstantSpace {
public void inOrderTraversal(BinaryTree<Integer> tree) {
BinaryTree<Integer> prev = null;
BinaryTree<Integer> current = tree;
List<Integer> result = new ArrayList<>();
while (current != null) {
BinaryTree<Integer> next;
// If previous node equal to parent means we are in the left tree
if (current.parent == prev) {
//Start iterating through the left side tree
if (current.left != null) {
next = current.left;
} else {
result.add(current.data);
next = (current.right != null ? current : current.parent);
}
} else if (prev == current.left) {
// If previous is current.left that means we just finished going through left node
// so add current data to list and start moving in right direction
result.add(current.data);
next = (current.right != null ? current : current.parent);
} else {
//Done with both right and left sibling so move up
next = current.parent;
}
prev = current;
current = next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment