Information about Tree : Tree Introduction
Pre-Order Traversal in Binary Tree
Post-Order Traversal in Binary Tree
In Order Traversal in Binary Tree: First we traversal through Left child, Node and then right child. Left child should be traversed before the Parent Node traversing, Right child should be traversed after parent node.
Recursive Way:
Iterative Way
Pre-Order Traversal in Binary Tree
Post-Order Traversal in Binary Tree
In Order Traversal in Binary Tree: First we traversal through Left child, Node and then right child. Left child should be traversed before the Parent Node traversing, Right child should be traversed after parent node.
- Traverse the left subtree by recursively calling the in-order function.
- Display the data part of root element (or current element).
- Traverse the right subtree by recursively calling the in-order function.
Recursive Way:
public void inOrderRecusriveWay(BinaryDataTree<Integer> root) {
if (root == null) {
return;
}
inOrderIterativeWay(root.getLeft());
System.out.print(root.getData() + " ");
inOrderIterativeWay(root.getRight());
}
Iterative Way
public void inOrderIterativeWay(BinaryDataTree<Integer> root) {
Stack<BinaryDataTree<Integer>> s = new Stack<BinaryDataTree<Integer>>();
if (root == null) {
System.out.println("No Element In the Tree");
return;
}
while (true) {
while (root != null) {
s.push(root);
root = root.getLeft();
}
if (s.isEmpty()) {
break;
}
BinaryDataTree temp = s.pop();
System.out.print(temp.getData() + " ");
root = temp.getRight();
}
}
No comments:
Post a Comment