Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main{
- public static void main(String[] args) {
- BinaryTree bt = new BinaryTree();
- bt.add(4);
- bt.add(1);
- bt.add(5);
- bt.add(3);
- bt.add(3);
- }
- }
- class BinaryTree{
- private class Node{
- int data;
- Node left;
- Node right;
- public Node(int data){
- this.data = data;
- left = null;
- right = null;
- }
- }
- Node root;
- int size;
- public BinaryTree(){
- root = null;
- size = 0;
- }
- public BinaryTree(int data){
- root = new Node(data);
- size = 1;
- }
- public void add(int data){
- if(size == 0){
- root = new Node(data);
- size++;
- } else {
- Node current = root;
- boolean found = false;
- while(!found){
- if(current.data >= data){
- if(current.left != null){
- current = current.left;
- } else {
- found = true;
- }
- } else if(current.data < data){
- if(current.right != null){
- current = current.right;
- } else{
- found = true;
- }
- }
- }
- if(current.data >= data){
- current.left = new Node(data);
- } else {
- current.right = new Node(data);
- }
- size++;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement