Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to build an unsorted binary tree in java?

I need to create an unsorted binary tree (one requirement is that it is unsorted) that holds a String as its value. My class outline looks like this:

public class Node {

 private String desc;
 private Node leftNode = null;
 private Node rightNode = null;

 public Node(String desc) {
  this.desc = desc;
 }

 public String getDesc() {
  return desc;
 }

 public Node getLeftNode() {
  return leftNode;
 }

 public Node getRightNode() {
  return rightNode;
 }
}

Eventually I want to be able to replace any node that matches a String description with a new node that has a new description (including duplicates with the old description).

So my question is, what is the best way to handle the insertion of Nodes when creating an unsorted binary tree?

I thought of two ways. The first would be to just have two methods, setLeftNode(Node root, String desc) and setRightNode(Node root, String desc) that someone could call with a Node of their choice as the root. If there already is a left/right Node, then it would just advance down until it hit a node that didn't have a left Node. But this could introduce problems by producing super large heights.

The second way I thought of would be to have a dedicated root Node, in this case the first Node created, and then to just build new Nodes in order.

So what is the best way to create an unsorted binary tree?

like image 529
Alex Avatar asked May 10 '15 01:05

Alex


People also ask

Can binary search tree be unsorted?

So, the answer is NO, it is not possible to use or implement Binary Search on unsorted arrays or lists, because, the repeated targeting of the mid element of one half depends on the sorted order of data structure.

Is binary tree always sorted?

Yes, it is. Since the elements of the BST satisfy a total preorder, an in-order traversal of the BST must produce those elements in order (Ex: prove it). It is equivalent to state that if we had stored a BST's keys, by an in-order traversal, in an array, the array would be sorted.

What is the time complexity of creating binary search tree?

Therefore, searching in binary search tree has worst case complexity of O(n). In general, time complexity is O(h) where h is height of BST.

How to construct Balanced binary tree?

Creating a Balanced BST First of all, let's think about the best node to put as the root. Since we need the tree to be balanced, we must put the middle value as the root. After that, we can add the values before the middle to the left of the tree. Therefore, all smaller values will be added to the left subtree.


3 Answers

public class BinaryTree{
    private BinaryTree right;
    private BinaryTree left;
    private String data;        

    public BinaryTree(String s){
        data = s;
        right = null;
        left = null;           
    }

    public void setLeft (BinaryTree l){ left  = l; }
    public void setRight(BinaryTree r){ right = r; }        
}

Your question suggests that the tree should be balanced and so on insertion of an element, you should recursively check number of nodes at each side of the tree:

public int checkTree(){
    if(left == null && right == null){
        return 1;
    }else if(left == null){
        return 1 + right.checkTree();
    }else if(right == null){
        return 1 + left.checkTree();
    }else{
        return 1 + left.checkTree() + right.checkTree();
    }
}

public void insert(BinaryTree bt){
    if(left == null){
        setLeft(bt);
    }else if(right == null){
        setRight(bt);
    }else{
        if(left.checkTree() <= right.checkTree()){
            left.insert(bt);
        }else{
            right.insert(bt);
        }
    }
}






EDITED:

public class BinaryTree {
    private BinaryTree right;
    private BinaryTree left;
    private String data;
    private int weight;

    public BinaryTree(String s){
        data = s;
        right = null;
        left = null; 
        weight = 1;
    }    

    public void setLeft (BinaryTree l){ 
        left  = l;
        weight++;
    }

    public void setRight(BinaryTree r){
        right = r;
        weight++;
    } 

    public int getWeight(){ return weight; }

    public void insert(BinaryTree bt){
        if(left == null){
            setLeft(bt);
        }else if(right == null){
            setRight(bt);
        }else{
            if(left.getWeight() <= right.getWeight()){
                left.insert(bt);
                weight++;
            }else{
                right.insert(bt);
                weight++;
            }
        }
    }    
}    
like image 86
Suspended Avatar answered Oct 21 '22 08:10

Suspended


by definition a binary tree has its lowest elements on the left, and the highest on the right. But if you really want that all messed up (sorted) you can call a rand function that results in 0 or 1, and if 0 then go to left, if 1 go to right, randomly. That will result in an unsorted tree

like image 26
João Vilaça Avatar answered Oct 21 '22 10:10

João Vilaça


Eventually I want to be able to replace any node that matches a String description with a new node that has a new description (including duplicates with the old description).

For that you will have to search your entire tree as:

private Node searchBasedOnValue(String desc, Node currentNode)
{  
    Node result = null
    if (currentNode == null)
        return null;
    if (currentNode.getDesc().equals(desc)) 
        return currentNode ;
    if (currentNode.getLeftNode() != null)
        result = searchBasedOnValue(desc,currentNode.getLeftNode());
    if (result == null)
        result = searchBasedOnValue(desc,currentNode.getRightNode());
    return result;
}

IMO, a regular Binary Tree is never sorted the one which is sorted is called Binary Search Tree. For insertion you need to handle the way you want it. May be you can insert nodes alternatively to left and right child of your tree so that it is balanced to some extent. That is up to you how you take care of that.

I have not seen much practical usage for regular Binary Tree as most of the times we use Binary Search Tree which have better performance (lg(n)) in terms of insertion, deletion and lookup.

like image 24
akhil_mittal Avatar answered Oct 21 '22 09:10

akhil_mittal