Skip to content

Instantly share code, notes, and snippets.

@anil477
Created June 29, 2017 20:42
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 anil477/cd66519fd967a9a5c784c80adc20bf35 to your computer and use it in GitHub Desktop.
Save anil477/cd66519fd967a9a5c784c80adc20bf35 to your computer and use it in GitHub Desktop.
Binary Tree - Inorder Traversal - Using Stack (no recursion)
// non-recursive java program for inorder traversal
/* importing the necessary class */
import java.util.Stack;
/* Class containing left and right child of current
node and key value*/
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
/* Class to print the inorder traversal */
class BinaryTree {
Node root;
void inorder() {
Stack<Node> stack = new Stack<Node>();
Node node = root;
while(node!=null){
stack.push(node);
node = node.left;
}
while(stack.size() > 0) {
Node temp = stack.pop();
System.out.println(" " + temp.data);
if(temp.right !=null) {
temp = temp.right;
while(temp!=null) {
stack.push(temp);
temp = temp.left;
}
}
}
}
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.inorder();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment