Add trees pre in post traversal java (#178)

* add pre, in and post traversal trees in java

* Update README.md

* update line 49 to pass lint test

change "System.out.print("\n\nin order: "); 
to 
System.out.println("\n");
System.out.print("in order: ");
pull/191/head
Toihir Halim 2021-04-14 17:31:22 +02:00 committed by GitHub
parent ca93cfa934
commit 0ca911387b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 80 additions and 0 deletions

View File

@ -5,3 +5,7 @@
1. [Pre, In & Post Order Traversals](c-or-cpp/pre-in-post-traversal.cpp) 1. [Pre, In & Post Order Traversals](c-or-cpp/pre-in-post-traversal.cpp)
2. [Level Order Traversal](c-or-cpp/level-order-traversal.cpp) 2. [Level Order Traversal](c-or-cpp/level-order-traversal.cpp)
3. [Build Binary Tree using Pre,In & Post Order](c-or-cpp/build-binary-tree.cpp) 3. [Build Binary Tree using Pre,In & Post Order](c-or-cpp/build-binary-tree.cpp)
### Java
1. [Pre, In & Post Order Traversals](java/pre_in_post_traversal.java)

View File

@ -0,0 +1,76 @@
class Node{
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
}
public class pre_in_post_traversal{
public static void preOrder(Node node){
if (node == null) return;
System.out.print(node.value + ", ");
preOrder(node.left);
preOrder(node.right);
}
public static void inOrder(Node node){
if(node == null) return;
inOrder(node.left);
System.out.print(node.value + ", ");
inOrder(node.right);
}
public static void postOrder(Node node){
if(node == null) return;
postOrder(node.left);
postOrder(node.right);
System.out.print(node.value + ", ");
}
public static void main(String [] args){
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(7);
root.left.right = new Node(6);
root.left.left = new Node(1);
root.right.right = new Node(9);
System.out.print("pre order: ");
preOrder(root);
System.out.println("\n");
System.out.print("in order: ");
inOrder(root);
System.out.print("\n\npost order: ");
postOrder(root);
}
}
/*
tree structure:
4
/ \
2 7
/ \ \
1 6 9
to run the file:
javac .\pre_in_post_traversal.java
java pre_in_post_traversal
results:
pre order: 4, 2, 1, 6, 7, 9,
in order: 1, 2, 6, 4, 7, 9,
post order: 1, 6, 2, 9, 7, 4,
*/