Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added code for preorder traversal of Tree #21

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions Preorder_Tree_Traversal.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Node {
int key;
Node left, right;

public Node(int item)
{
key = item;
left = right = null;
}
}

class BinaryTree {
Node root;
BinaryTree() { root = null; }
void printPreorder(Node node)
{
if (node == null)
return;

// traverse the root node
System.out.print(node.key + " ");
// traverse the left child
printPreorder(node.left);
// traverse the right child
printPreorder(node.right);
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(12);
tree.root.right = new Node(9);
tree.root.left.left = new Node(5);
tree.root.left.right = new Node(6);

System.out.println("\nPreorder traversal of binary tree is ");
tree.printPreorder(tree.root);
}
}