Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active June 30, 2017 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/e336ec1ebb1de0bcf8937ec86c582ce7 to your computer and use it in GitHub Desktop.
Save anil477/e336ec1ebb1de0bcf8937ec86c582ce7 to your computer and use it in GitHub Desktop.
Binary Tree Traversal - InOrder, PreOrder, PostOrder - Depth First Traversal
class Node
{
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
class BinaryTree
{
// Root of Binary Tree
Node root;
BinaryTree()
{
root = null;
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
Node second = new Node(2);
second.left = new Node(4);
second.right = new Node(5);
tree.root.left = second;
tree.root.right = new Node(3);
System.out.println(" Inorder ");
tree.printInorder();
System.out.println(" Preorder ");
tree.printPreorder();
System.out.println(" Postorder ");
tree.printPostorder();
}
public void printPostorder()
{
postorder(root);
}
public void postorder(Node root)
{
// Left, Right, Root
if(root == null) {
return;
}
postorder(root.left);
postorder(root.right);
System.out.print(root.key + " ");
}
public void printPreorder()
{
preorder(root);
}
public void preorder(Node root)
{
// Root Left Right
if(root == null) {
return;
}
System.out.print(root.key + " ");
preorder(root.left);
preorder(root.right);
}
public void printInorder()
{
inorder(root);
}
public void inorder(Node root)
{
// Left Root Right
if(root == null) {
return;
}
inorder(root.left);
System.out.print(root.key + " ");
inorder(root.right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment