Reputation: 1
How do I turn this into a preorder and a postorder traversal? This code only traverses a tree in an inorder style.
void inorder() {
inorderRec(root);
}
// Inorder Traversal
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.key + " -> ");
inorderRec(root.right);
}
}
Upvotes: 0
Views: 533
Reputation: 31
void preOrder(Node root)
{
if (root) {
System.out.print(root.key + " -> ");
preOrder(root.left);
preOrder(root.right);
}
}
void postOrder(Node root)
{
if (root)
{
postOrder(root.left);
postOrder(root.right);
System.out.print(root.key + " -> ");
}
}
Upvotes: 0
Reputation: 11620
You can just change the order of statements:
void preOrderRec(Node root) {
if (root != null) {
System.out.print(root.key + " -> ");
inorderRec(root.left);
inorderRec(root.right);
}
void postOrderRec(Node root) {
if (root != null) {
inorderRec(root.left);
inorderRec(root.right);
System.out.print(root.key + " -> ");
}
Upvotes: 1