Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active May 26, 2018 23:40
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 thmain/a4537be81ac0a33de62f to your computer and use it in GitHub Desktop.
Save thmain/a4537be81ac0a33de62f to your computer and use it in GitHub Desktop.
import java.util.Stack;
public class InorderIretation {
public void inorderRecursive(Node root) {
if (root != null) {
inorderRecursive(root.left);
System.out.print(root.data + " ");
inorderRecursive(root.right);
}
}
public void inorderIteration(Node root) {
Stack<Node> s = new Stack<Node>();
while (true) {
// Go to the left extreme insert all the elements to stack
while (root != null) {
s.push(root);
root = root.left;
}
// check if Stack is empty, if yes, exit from everywhere
if (s.isEmpty()) {
return;
}
// pop the element from the stack , print it and add the nodes at
// the right to the Stack
root =s.pop();
System.out.print(root.data + " ");
root = root.right;
}
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
InorderIretation i = new InorderIretation();
i.inorderRecursive(root);
System.out.println();
i.inorderIteration(root);
}
}
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment