import java.util.Stack;
//Inorder Tree Traversals : Iterative
Model(Non-Recursive way)
class BinaryTreeInOrderTraversalIterativeModel {
class TreeNode {
TreeNode left, right;
int data; // considering integer data.
public TreeNode(int dataItem) {
this.data = dataItem;
left = null;
right = null;
}
}
TreeNode root;
BinaryTreeInOrderTraversalIterativeModel()
{
root = null;
}
void printInOrderTraversal(TreeNode treeNode) {
if(treeNode == null)
return;
Stack<TreeNode>
s = new Stack<TreeNode>();
TreeNode currentNode = root;
while(!s.isEmpty() || currentNode != null) {
if(currentNode != null) {
s.push(currentNode);
currentNode = currentNode.left;
} else {
currentNode = s.pop();
System.out.println(currentNode.data);
currentNode = currentNode.right;
}
}
}
void printInOrder() {
printInOrderTraversal(root);
}
public static void main(String[] args) {
BinaryTreeInOrderTraversalIterativeModel
tree = new
BinaryTreeInOrderTraversalIterativeModel();
tree.root = new TreeNode(1);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.left.left = new TreeNode(4);
tree.root.left.right = new TreeNode(5);
tree.root.right.left = new TreeNode(6);
tree.root.right.right = new TreeNode(7);
tree.printInOrder();
}
}
//Time Complexity: O(n). Space Complexity: O(n).
|
Thanks..!!
No comments:
Post a Comment