Skip to content

Instantly share code, notes, and snippets.

@BetelGeuseee
Created May 21, 2020 16:50
Show Gist options
  • Save BetelGeuseee/ee769f19cfcd22de24f6cadf1e9e4f43 to your computer and use it in GitHub Desktop.
Save BetelGeuseee/ee769f19cfcd22de24f6cadf1e9e4f43 to your computer and use it in GitHub Desktop.
Binary tree traversal and insertion
package TreeProblems;
public class BinaryTree {
static class Node{
int value;
Node left,right;
Node(int value){
this.value=value;
left=null;
right=null;
}
}
public void insert(Node node,int value){
if(value<node.value){
if(node.left!=null){
insert(node.left,value);
}
else{
System.out.println(value + " is inserted to the left of "+node.value);
node.left=new Node(value);
}
}
else if(value>node.value){
if(node.right!=null){
insert(node.right,value);
}
else{
System.out.println(value+" is inserted to the right of "+node.right);
node.right=new Node(value);
}
}
}
public void traverseInOrder(Node node){
if(node!=null){
traverseInOrder(node.left);
System.out.print(" "+node.value);
traverseInOrder(node.right);
}
}
public static void main(String[] args){
BinaryTree tree = new BinaryTree();
Node root = new Node(5);
tree.insert(root, 2);
tree.insert(root, 4);
tree.insert(root, 8);
tree.insert(root, 6);
tree.insert(root, 7);
tree.insert(root, 3);
tree.insert(root, 9);
tree.traverseInOrder(root);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment