Created
June 29, 2017 20:42
-
-
Save anil477/cd66519fd967a9a5c784c80adc20bf35 to your computer and use it in GitHub Desktop.
Binary Tree - Inorder Traversal - Using Stack (no recursion)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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